JavaScript listening and disabling browser carriage return event instance _javascript tips

Source: Internet
Author: User
Tags html form

JS Monitor Browser return event, you can support ie6+, Firefox, Google and other browsers.

Copy Code code as follows:

<script type= "Text/javascript" >
Registering keyboard events
Document.onkeydown = function (e) {
Catch carriage return events
var ev = (typeof event!= ' undefined ')? Window.event:e;
if (Ev.keycode = = 13) {
Alert (' captures the carriage return event! ');
}
}
</script>
<body/>

So, how do I capture the carriage return event for a specified DOM object? Here take the input tag as an example to illustrate:

Copy Code code as follows:

<script type= "Text/javascript" >
Registering keyboard events
Document.onkeydown = function (e) {
Catch carriage return events
var ev = (typeof event!= ' undefined ')? Window.event:e;
if (Ev.keycode = && Document.activeElement.id = = "MSG") {
Alert ("Get to Content:" + document.activeElement.value);
}
}
</script>
<body>
<input type= "text" id= "msg" value= "/>
</body>

So, JS How to disable browser carriage return event? We know that in an HTML form area, the default behavior of the browser when you press ENTER is to submit the form automatically. Here is an example of how JS disables the browser carriage return event:

Copy Code code as follows:

<script type= "Text/javascript" >
Registering keyboard events
Document.onkeydown = function (e) {
Catch carriage return events
var ev = (typeof event!= ' undefined ')? Window.event:e;
if (Ev.keycode = && Document.activeElement.id = = "MSG") {
Return false;//disabled carriage returns events
}
}
</script>
<body>
<form action= "form.php" >
<input type= "text" id= "msg" Name= "msg" value= ""/>
<input type= "Submit" value= "Submit"/>
</form>
</body>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.