11

Found this script:


function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

document.onkeypress = stopRKey;


Only issue, it also stops enter key being used in textarea. Which is a hassle.

I have toyed with using: onkeypress="return handleEnter(this, event)"

But our forms are extremely complex, and I am looking for a cleaner way of doing things.

422
  • 5,638
  • 23
  • 80
  • 135

3 Answers3

29

You need to check the nodeName or tagName of the event target here, like this:

if (evt.keyCode == 13 && node.nodeName != "TEXTAREA") { return false; }

I noticed after this was accepted that you are already using jQuery, you can just replace all your code above with this:

$(document).keypress(function (e) {
  if(e.which == 13 && e.target.nodeName != "TEXTAREA") return false;
});
Oren A
  • 5,680
  • 6
  • 41
  • 62
Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
  • do we amend that code as is, or do we need to change nodeName ? – 422 Nov 19 '10 at 02:17
  • @422 - this is meant to replace the `if ((evt.keyCode == 13) && (node.type=="text")) {return false;}` line of code...this way it returns `false` is it's enter and it's NOT a ` – Nick Craver Nov 19 '10 at 02:18
  • Yep, he's right. Basically what I said except use `.nodeName` instead of `.type`. Damn. – Ben Nov 19 '10 at 02:22
  • @422 - welcome, there's also a much easier jQuery solution since you're already including it, added it to the answer. – Nick Craver Nov 19 '10 at 02:27
  • Tried:
    
     
    
    But isnt working, have i cocked something up ?
    – 422 Nov 20 '10 at 01:25
2

I think you can just change this line

if (evt.keyCode == 13 && node.type == "text") {
  return false;
}

to

if (evt.keyCode == 13 && node.type != "TEXTAREA") {
  return false;
}
Ben
  • 51,262
  • 47
  • 169
  • 217
  • Nope, doesnt work for us. Still tries to submit form. Will keep playing with it, as this seems cleanest way of achieveing what we want to do – 422 Nov 19 '10 at 02:11
  • Sorry should be `.nodeName`. (But @Nick Craver found that bug, not me.) – Ben Nov 19 '10 at 02:23
0

If you use jquery (highly recommended) then this will automatically add the function to allow use of the enter key:

$("textarea").focus(function () { 
     $(this).keypress(handleEnter);
}); 
Ricky Cook
  • 909
  • 8
  • 14