Monday 17 December 2007

Form submit weirdness in Opera 9.20

Here's one for you:

I have a few input form elements on a page, one of them is of type 'submit'. Because I don't use a form to submit this information, I set an event listener for one of the inputs like so: onkeypress="if(event.keyCode==13)myAction()" so that if enter is pressed, an action is performed. Similarly for the 'submit' input onclick="myAction()", so if the button is clicked the same action will be performed.

Here's what happens: if the enter key is pressed in the text control, myAction is executed twice. It's executed only once if I click on the button...

I investigated the problem and here are a few observations:

  • If the type of the submit element is changed to 'button' the action is performed only once when enter is pressed, as expected

  • If I remove the event listener from the text input element and leave the type of the 'submit' element unchanged, myAction is executed only once, as expected

  • What happens in myAction does not affect the form elements in any way, myAction can be replaced with alert

  • This behaviour doesn't happen in Firefox

  • In Firefox, only if the elements are in a form (and they are not in my case) then the form is submitted when enter is pressed in one of the text input elements



My conclusion: Opera detects a 'submit' element and launches a click event on it when enter is pressed in one of the text input elements, assuming that they're all part of a form. I think this is not something a web developer would expect, would you?

I need the event listeners for Firefox, so I'm going to change the submit element to 'button' which is more appropriate anyway.

No comments: