Viewed   88 times

I have the following javascript in my page which does not seem to be working.

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

 Answers

4

If keyCode is not caught, catch which:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

EDIT: missed it, it's better to use keyup instead of keypress

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

EDIT 3: Changed bind() to on()

Tuesday, November 22, 2022
 
2

If you have no other handlers bound, you could do something like this:

$('#imageaddform').submit(function(e) {
    e.preventDefault(); // don't submit multiple times
    this.submit(); // use the native submit method of the form element
    $('#imagefile').val(''); // blank the input
});
Saturday, September 17, 2022
 
lku
 
lku
2

span is not a form element. Form elements are inputs, selects, radios, textareas, etc. That is why it works when you change it to an input.

Saturday, August 6, 2022
4

If you say you use anyway the JS to submit the data in the form why not cancel the default behaviour of the browser with <form onsubmit="return false;">. This way no matter if you press the submit button or press enter in an input it won't be sent. The onsubmit="return false" shouldn't interfere with calling the submit() method on the form from JS.

Friday, December 9, 2022
 
4
if (document.addEventListener) {
    document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
    document.getElementById('strip').onkeypress = HandleKeyPress;
}

function HandleKeyPress(e) {
    switch (e.keyCode) {
        case e.DOM_VK_ENTER:
        if (e.preventDefault)
            e.preventDefault();
    else e.returnValue = false;
    }
}

EDIT due to original Question edit:

all you need is:

$(document).ready(function()
{
    $("#frmUserListSearch").keyup(function(event)
        {
            if(event.keyCode == 13)
            {     
                SearchUser();
                if (e.preventDefault)
                    e.preventDefault();
                else e.returnValue = false;
            }
        });
});

edited to reflect comment

Saturday, October 1, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :