JS monitors browser carriage return events and can support browsers such as ie6+, Firefox, Google, etc.
The code copy is as follows:
<html>
<head>
<script type="text/javascript">
//Register keyboard event
document.onkeydown = function(e) {
//Catch the carriage return event
var ev = (typeof event!= 'undefined') ? window.event : e;
if(ev.keyCode == 13) {
alert('Catched the Enter event!');
}
}
</script>
</head>
<body />
</html>
So, how to catch the carriage return event of a specified DOM object? Here is an example of the input tag:
The code copy is as follows:
<html>
<head>
<script type="text/javascript">
//Register keyboard event
document.onkeydown = function(e) {
//Catch the carriage return event
var ev = (typeof event!= 'undefined') ? window.event : e;
if(ev.keyCode == 13 && document.activeElement.id == "msg") {
alert("get content:" + document.activeElement.value);
}
}
</script>
</head>
<body>
<input type="text" id="msg" value="" />
</body>
</html>
So, how to disable browser carriage return event in js? We know that in the HTML form area, the default behavior of the browser when pressing Enter is to automatically submit the form. Here is an example to illustrate how to disable browser enter event by js:
The code copy is as follows:
<html>
<head>
<script type="text/javascript">
//Register keyboard event
document.onkeydown = function(e) {
//Catch the carriage return event
var ev = (typeof event!= 'undefined') ? window.event : e;
if(ev.keyCode == 13 && document.activeElement.id == "msg") {
return false;//Disable the return event
}
}
</script>
</head>
<body>
<form action="form.php">
<input type="text" id="msg" name="msg" value="" />
<input type="submit" value="submit"/>
</form>
</body>
</html>