Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need Javascript function to disable enter key

Tags:

javascript

I need to use JS function to disable enter key. I'm currently facing an issue with my Spring form

<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

HTTP Status 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

like image 262
Ali Taha Ali Mahboub Avatar asked May 16 '11 12:05

Ali Taha Ali Mahboub


2 Answers

This should work:

Markup:

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

JavaScript:

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

Live demo: http://jsfiddle.net/Fj3Mh/

like image 67
Šime Vidas Avatar answered Sep 18 '22 14:09

Šime Vidas


you need to address this in the keyup and keydown event. 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. 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.

like image 31
Charles Lambert Avatar answered Sep 17 '22 14:09

Charles Lambert