views:

583

answers:

5

I'm having trouble with events in Internet Explorer 7

When I have a form with TWO+ input[type=text] and I press Enter key 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('buttom::onClick');}">
</FORM>

BUT...

If a have only ONE input[type=text] and I press Enter key the submit button onClick event DOESN'T FIRES. Sample code:

<FORM onSubmit="{alert('form::onSubmit'); return false;}">
 <INPUT TYPE="text">
 <INPUT TYPE="submit" onClick="{alert('buttom::onClick');}">
</FORM>

Any Ideas?

A: 

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".

superjoe30
+3  A: 

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)?

DannySmurf
A: 

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.

bubbassauro
A: 

Out of curiosity, are you using a DOCTYPE, and if so, which one? I'm not saying incompatabilities with the DOCTYPE are the issue, but quirks mode is something to rule out before trying anything else.

Brian Warshaw
A: 

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

mplungjan
Why would I be voted up and down on this comment???
mplungjan
I didn't downvote, but I'm having trouble parsing the last sentence. ("never do anything onClick of a submit button but always do it in ... a button onClick"???)
Tim Pietzcker