Skip to content Skip to sidebar Skip to footer

Form Should Not Submit On Enter If Focus Is Not On Submit Button

I have a requirement where user cannot submit the form if he press enter key unless focus will be on submit button. Using following code, I am able to do that, but now the issue is

Solution 1:

If you had created a JsFiddle it would be easier to help. However, I'm thinking you should do something like this:

if($focusedItem.attr('id') == 'submitButton') {
    if (event.keyCode == 13) {
        submit the form
    }
}elseif ($focusedItem.attr('id') == 'Anothertextarea') {
    if (event.keyCode == 13) {
        do something special
    }
}else{
    if (event.keyCode == 13) {
    returnnull;
    }
}

Solution 2:

Remove the line event.stopPropagation(); from your script, you need only the preventDefault() (prevents the submit).

When you do stopPropagation() you are stopping all other keypress events on the element.

Solution 3:

Try that and see if it fits your needs:

--DEMO--

$(document).on('submit', 'form', function (e) {
    e.preventDefault();
}).on('click', ':submit', function (e) {
    if (!$(document.activeElement).is(':submit')) return;
    var form = $(this).closest('form').length ? $(this).closest('form')[0] : $('#' + $(this).attr('form'))[0];
    form.submit();
});

Solution 4:

Maybe I'm missing the point, this is basically a standard html issue.

Don't give the form an submit action (move it to a click event directly on the button) and change all button types to button instead of submit.

I can't remember if simply removing the submit from the form is enough. If not then just do onSubmit="return false;" I think that does it.

However as a note the requirement for this as a global behavior is probably wrong and if its for the government then you will probably get in trouble since its not compliant with accessibility guidelines.

Post a Comment for "Form Should Not Submit On Enter If Focus Is Not On Submit Button"