简体   繁体   中英

on('submit' works when clicking the <button> but not when pressing enter on an input field

I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.

I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?

$('#form').on('submit', function (e) {

    e.preventDefault();

    var email = $('#email').val();

    function validateEmail(email) { 
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    } 

});


<form id="form">
    <input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
    <button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>

If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.


You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic

You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).

If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/

You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:

return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!

A tip: if you're working in html5, you can use this and the browser will do validating for you:

<input type="email" />

您需要插入一个不可见的输入类型Submit才能起作用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM