views:

1532

answers:

3

When using a form with many text input, WebKit/Safari/Google Chrome submits the form when ''enter'' is pressed in any input element. Even if there is no submit input element and no onclick handler registered.

See for instance this sample code:

<html>
    <body>
        <form method="POST" action=".">
            <ul>
                <li><input type="text" name="foo" value="<?=rand()?>"/></li>
                <li><input type="text" name="bar" value="<?=$_POST['foo']?>"/></li>
            </ul>
        </form>
    </body>
</html>

When pressing enter in any of the two text input elements, the form is submitted.

Since I'm handling my form in JavaScript with asynchronous HTTP requests, I need to prevent this behavior. I could register a custom handler for the keypressed event to preventDefault and stopPropagation . But its seems ugly and is not really practical when new text input elements are added dynamically.

+3  A: 

Listen for the onsubmit event on the form and return false.

Daniel A. White
Damn, I was a minute too slow
Mike Robinson
+1  A: 

If you don't ever want the form to submit, don't include a <form> element at all. It's valid to include free-standing form field elements.

value="<?=$_POST['foo']?>"

XSS vulnerability. You need to htmlspecialchars() all text-to-HTML output.

bobince
A: 

Daniel A. White is right but since i got a little bit confused by the answer maybe it should be clearly stated that the return false should be on the event

function goWithSubmit(e) { if (e) e.returnValue=false; }

shayuna