Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable the normal submit on enter behavior on a text input and replace it with a function of my own?

I've tried quite some fixes i found on stackoverflow and elsewhere but I couldn't get any of them to work properly. They either disable the enter key everywhere or just don't work at all (or they're not properly explained).

I need the normal submit on enter key behavior to work on all the other elements except this one text input and for it to be replaced with my own function when the text input is selected.

like image 380
Bogdan Avatar asked Mar 27 '12 08:03

Bogdan


People also ask

How do you disable form submit on Enter?

addEventListener("submit",function(e){e. preventDefault(); return false;}); This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

How do you make HTML input submit on enter?

You need to add an <input type="submit"> and hide it with CSS so that the browser knows what to trigger when enter is pressed, yet still not show a button. For the sake of accessibility and ease of use, I'd show the button even if not that many people use it (enter is much nicer).

What happens when enter text in input box and press Tab key?

when you press tab then it should tab to next blank text input box javascript without using tab index - Stack Overflow.


2 Answers

How to get whether the Enter is pressed?

$('input.the-one-text-input').keydown(function(e) {
  if(e.keyCode == 13) { // enter key was pressed
    // run own code
    return false; // prevent execution of rest of the script + event propagation / event bubbling + prevent default behaviour
  }
});

Also note this comment on that page:

** If anyone has reached this from Google (like I did), know that "keyup" instead of "keypress" works in Firefox, IE, and Chrome. "keypress" apparently only works in Firefox.

Which isn't 100% correct anymore, since it also works works in Chrome. However it wouldn't surprise me if it still doesn't work in IE.

like image 51
PeeHaa Avatar answered Oct 31 '22 02:10

PeeHaa


http://jsfiddle.net/yzfm9/9/

Basically check which input is focused and do custom stuff depending on it

HTML

<form id="nya">
    username <input type="text" id="input_username" /><br/>
    email <input type="text" id="input_email" /><br/>
    hobby <input type="text" id="input_hobby" /><br/>
    <input type="submit" />
</form>

JS

$('#nya').submit(function() {
    var focusedId = ($("*:focus").attr("id"));
    if(focusedId == 'input_email') {
       // do your custom stuff here

       return false;
    }
});
like image 41
Andreas Wong Avatar answered Oct 31 '22 02:10

Andreas Wong