Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick doesn't fire with only one input when pressing enter

I'm having trouble with events in Internet Explorer 7.

When I have a form with two or more input[type=text] and I press enter, the events occurs in this order:

  1. submit button (onClick)
  2. form (onSubmit)

Sample code:

<form onSubmit="{alert('form::onSubmit'); return false;}">
    <input type="text">
    <input type="text">
    <input type="submit" onClick="{alert('button::onClick');}">
</form>

If I have only one input[type=text] and I press enter the submit button onClick event doesn't fire. Sample code:

<form onSubmit="{alert('form::onSubmit'); return false;}">
    <input type="text">
    <input type="submit" onClick="{alert('button::onClick');}">
</form>
like image 596
Daniel Silveira Avatar asked Aug 12 '08 23:08

Daniel Silveira


4 Answers

The button's onclick should (I think) only fire if the button is actually clicked (or when the focus is on it and the user clicks enter), unless you've added logic to change that.

Is the addition of the extra textbox possibly changing the tab order of your elements (perhaps making the button the default control in that case)?

like image 176
TheSmurf Avatar answered Oct 25 '22 03:10

TheSmurf


From the dawn of browsers, a single input field in a form would submit on enter with or without a submit button. This was to make it simpler for people to search a site from a single search field.

If you need to execute some javascript in a form, it is safer practice to use the onsubmit of the form (and return false to stop submission) rather than executing script in the onClick of the submit button. If you need to execute javascript from a button, use type="button" instead of type="submit" - hope this clarified what I meant

like image 25
mplungjan Avatar answered Oct 25 '22 04:10

mplungjan


If you want code to run when the user presses enter, just use the onSubmit handler.

If you want code to run when the user presses the button, and not when the user presses enter, use a button other than type="submit".

like image 33
andrewrk Avatar answered Oct 25 '22 02:10

andrewrk


Interestingly, if you click on the screen (remove the focus from the textbox) on second example with only one textbox, the event onClick fires... So it's not an expected behaviour since it only occurs when you have just one textbox and you have the focus on the textbox.
I'm afraid you've found a bug on the browser and you'll have to find a workaround, or avoid using the onClick event in that case.
I use the onSubmit event for validations because it's a "safer" event that is more likely to work on different browsers and situations.

like image 36
bubbassauro Avatar answered Oct 25 '22 04:10

bubbassauro