0

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>
Martijn
  • 15,791
  • 4
  • 36
  • 68
Dan P.
  • 1,707
  • 4
  • 29
  • 57

2 Answers2

0

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" />
Martijn
  • 15,791
  • 4
  • 36
  • 68
  • You are describing the problem I am having -- I don't understand why pressing enter on the input doesn't trigger the submit eventhandler.. – Dan P. Apr 15 '14 at 20:59
-1

You need to insert an invisible input type submit for this to work.

maak.
  • 21
  • 5
  • Not the -1, but he has a submit, so this can't be the problem. Also, after I tested his code, it worked. The problem isnt the eventhandler, the problem is (after I did some digging) that way he uses the function – Martijn Apr 15 '14 at 21:08
  • Martijn It might be working because of the particular browser you are using. I think maak's solution would work but it's clunky. – Stephen Apr 15 '14 at 23:25