JavaScript form submitting using an image is not working
-
13-09-2019 - |
Question
I have a FORM that I want to use an IMG, instead of an input button, to submit the form.
The code:
<form>
<input class="form_grey" value="Enter in City or Zipcode" type="text" id="city-field" name="city" onfocus="this.value='';" />
<a href="javascript:document.form.submit()"><img src="/images/btn.png" /></a>
</form>
When I type in the input field and Press ENTER (on my keyboard), the form submits correctly. BUT, if I type in the input field and click my image submit button, nothing happens.
Any ideas as to why my Javascript image form submit doesn't work?
Solution
Replace this:
<a href="javascript:document.form.submit()"><img src="/images/btn_search_listings.png" /></a>
With this:
<input type="image" src="/images/btn_search_listings.png" />
Using Javascript to have an image submit a form is not really necessary here as you have the image input type that behaves as a submit button. This will also make keyboard navigation work properly and be much more accessible overall.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow