Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable enter key on page, but NOT in textarea

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.

like image 900
422 Avatar asked Nov 19 '10 01:11

422


2 Answers

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;
});
like image 190
Nick Craver Avatar answered Sep 28 '22 12:09

Nick Craver


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;
}
like image 42
Ben Avatar answered Sep 28 '22 12:09

Ben