简体   繁体   English

我需要Javascript函数来禁用回车键

[英]I need Javascript function to disable enter key

I need to use JS function to disable enter key. 我需要使用JS函数来禁用回车键。 I'm currently facing an issue with my Spring form 我目前正面临着Spring表单的问题

<form:textarea path="name" onkeypress="return noenter()"

here is the function I currently using 这是我目前使用的功能

<script> function noenter() {   alert("Testing");
    return !(window.event && window.event.keyCode == 13); 
    } </script>

for some reason, the alert is working when I press on Enter key, but still facing same exception 出于某种原因,当我按下Enter键时警报正在工作,但仍然面临同样的异常

HTTP Status 415 - HTTP状态415 -

type Status report 类型状态报告

message 信息

description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (). 说明服务器拒绝此请求,因为请求实体的格式不受请求方法所请求的资源支持()。 Apache Tomcat/6.0.29 Apache Tomcat / 6.0.29

This should work: 这应该工作:

Markup: 标记:

<form:textarea path="name" onkeypress="return noenter(event)">

JavaScript: JavaScript的:

function noenter(e) {
    e = e || window.event;
    var key = e.keyCode || e.charCode;
    return key !== 13; 
}

Live demo: http://jsfiddle.net/Fj3Mh/ 现场演示: http //jsfiddle.net/Fj3Mh/

you need to address this in the keyup and keydown event. 你需要在keyup和keydown事件中解决这个问题。 The browser uses the enter key independent of the actual web page. 浏览器使用独立于实际网页的回车键。 So you will need to stop event propagation at the keyup or keydown event. 因此,您需要在keyup或keydown事件中停止事件传播。 By the time the keypress event has been emitted the browser itself has received it and there is no way to keep it from processing. 当按键事件被发出时,浏览器本身已经收到它,并且没有办法阻止它处理。 This is specific to the enter key and a few others. 这特定于输入键和其他一些键。 Character keys such as 'a' and 'b' do not suffer from this problem. 诸如“a”和“b”之类的字符键不会遇到此问题。

<script type="text/javascript"> 

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; 

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM