Marwelln
Marwelln

Reputation: 29413

Prevent jquery submit on enter press on specific field

How can I cancel the jquery submit from running when I press the enter key on a specific input field?

Something like this:

var $canSubmit = true;
$('#profile_form')
    .keyup(function(e){         
        if (e.keyCode == 13 && e.srcElement.name == 'countrySearch') {
            $canSubmit = false;
        } else
            $canSubmit = true;
    })
    .on('submit', function(e){
        e.preventDefault();
        console.log(e);

        if (!$canSubmit) return false;

        // first time enter is clicked when on countrySearch this is run as submit runs before keyup
        // i want all code here not to run when enter is clicked on input[name="countrySearch"]
    });

Upvotes: 2

Views: 723

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You shoud use keypress insted of keyup and e.target.name

var $canSubmit = true;
$('#profile_form').keypress(function(e) {
    if (e.keyCode == 13 && e.target.name == 'countrySearch') {
        $canSubmit = false;
    } else {
        $canSubmit = true;
    }
}).on('submit', function(e) {
    if (!$canSubmit) {
        return false;
    } else {
        alert('this would submit');
    }

});

fiddle here http://jsfiddle.net/tazcu/1/

Upvotes: 2

maxedison
maxedison

Reputation: 17553

Since you're using jQuery, I think you should be using e.which to get the key code. I might be wrong, but I think that provides a more cross-browser solution than e.keyCode.

Anyway, here's what you asked for:

$('[name=countrySearch]')
    .keydown(function(e){         
        if (e.which == 13) {
            e.preventDefault();
        }
    });

I think you actually want to bind to the keydown or keypress event here rather than keyup, but I might be wrong about that as well :) Regardless, rather than doing your e.srcElement.name check, you can simply bind the event to the countrySearch element itself. Then, if the key code ends up being 13, you just prevent the default action (which, in this case, would be submitting the form). No need to set a messy global variable that will get checked when the submit event gets fired, because the submit event simply won't get fired!

Upvotes: 0

Related Questions