jQuery, prevent form submit from enter but allow form submit by button click

14,201

Solution 1

I found the solution

$("#toteform").submit(function(e) {
    if (e.originalEvent.explicitOriginalTarget.id == "submit") {
        // let the form submit
        return true;
    }
    else {
        //Prevent the submit event and remain on the screen
        e.preventDefault();
        return false;
    }
});

Solution 2

Be careful with the e.originalEvent.explicitOriginalTarget.id approach. It only works on Gecko based browsers.

Related answer.

Would have used a comment but I don't have enough reputation :(

Solution 3

You can prevent form submit

$("#toteform").on('submit',function(e) {
    e.preventDefault();
});

and on click of submit button you can manually submit the form.

$("#submit").click(function() {
    $('#toteform').submit();
});
Share:
14,201
AdRock
Author by

AdRock

Father of 2, living with partner, finished at Exeter University

Updated on June 04, 2022

Comments

  • AdRock
    AdRock almost 2 years

    I have a form where in an input text box I enter a number and press ENTER and I use jQuery to append the value to a textarea. This all works fine.

    The problem I'm having is that if i add a submit button to submit the form, as soon as i press ENTER, it submits the form.

    What I want it to do is not submit the form on pressing enter but submit the form ONLY when the submit button is clicked.

    I've tried using preventDefault() and return false which will stop the form submitting on pressing ENTER but if i add a click event on the submit button to submit the form, it does nothing. I've put an alert in the click function before the submit and that fires but form doesn't submit

    <form id="toteform" method="post" action="blah.php">
        <input type="text" name="bin" id="bin" maxlength="4" autocomplete="off" />
    
        <input type="text" name="totes" id="tote" maxlength="4" autocomplete="off" />
    
        <input type="button" name="submit" class="submit" id="submit" value="Submit" />
    </form>
    

    jQuery

    $("#submit").click(function() {
        $('#toteform').submit();
    });
    
    $('#bin').focus();
    
    $('#bin').keypress(function(e) {
        if(e.which == 13) {
            $('#tote').focus();
        }
    });
    
    $('#tote').keypress(function(e) {
        if(e.which == 13) {
    
        // more code here to do other things
    
  • AdRock
    AdRock over 10 years
    Thanks for your reply. I changed the input type of button to submit and for both input types they still don't submit the form. I have added an alert within the #submit click event and as soon as you enter a value and press ENTER, the alert opens without the button click
  • MrMarlow
    MrMarlow almost 8 years
    Have another 10 rep to get your comment skillz up.