cristi _b
cristi _b

Reputation: 1813

Submit buttons and Enter key issues

I'm trying to prevent form submit if users has focus on any submit button or input type text (as in a filtering datagrid).

I'm considering 2 options

Is there a better way to do this?

Upvotes: 0

Views: 1057

Answers (2)

Chris Baker
Chris Baker

Reputation: 50592

If you add an onKeyPress event to the element in question, you can prevent the default action (form submission) by returning false from the function:

<input id="txt" type="text" onKeyPress="var key = event.keyCode || event.which; if (key == 13) return false;"></input>

Note that the which property of the keyboard event is deprecated, but you'll still want to check for it to support older user agents and/or Internet Exploder (reference).

If you don't want to use inline javascript (which is not recommended), you can instead attach an event. Also, it may be better to use the preventDefault (docs) method of the event object, as well as the stopPropagation method (docs) - the necessity for these methods this is highly dependent on what other events you have attached to the form or the elements:

var preventFormSubmit = function (event) {
    var key = event.keyCode || event.which;
    if (key != 13)
        return;
    if (event.stopPropagation) event.stopPropagation();
    else event.cancelBubble = true; // deprecated, for older IE
    if (event.preventDefault) event.preventDefault();
    else event.returnValue = false; // deprecated, for older IE
    return false;
};  
var target = document.getElementById('txt');
if (typeof target.addEventListener == 'function')
    target.addEventListener('keypress', preventFormSubmit, false);
else if (typeof target.attachEvent == 'function')
    target.attachEvent('onkeypress', preventFormSubmit);

There are other approaches to use, such as attaching a more complex onSumit handler to the form itself - this may be more appropriate if you're going to be doing further manipulation of the form or data before submitting (or using AJAX to submit the form data).

Upvotes: 2

cristi _b
cristi _b

Reputation: 1813

Solution

input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>

Link

http://stackoverflow.com/questions/1567644/submit-form-problem-enter-key

Question closed

Upvotes: 0

Related Questions