Home > Article > Web Front-end > How to register a carriage return event for a button (setting the default button) using javascript_javascript skills
The example in this article describes the method of javascript registering the carriage return event for the button (setting the default button). Share it with everyone for your reference. The details are as follows:
First of all, I have to say that I am really a novice when it comes to JS. Regarding JS and some JS frameworks such as JQuery, I am only in the stage of simple application. Of course, I am also constantly learning. I hope to share more experience in JS with you in the future. Let’s start with something appetizing today. Let’s talk about how to set a default button. That is, no matter whether the focus is on the button or not, as long as you press Enter, the click event of the button will be triggered.
The code is very simple. To complete this function, only a few lines of code are needed:
//为keyListener方法注册按键事件 document.onkeydown=keyListener; function keyListener(e){ // 当按下回车键,执行我们的代码 if(e.keyCode == 13){ //我们要做的事情 } }
Well, it seems a bit too simple. I feel a little embarrassed to finish a blog like this. Finally, let me attach an example of a small program for you:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计算器</title> <script type="text/javascript" > function calculate() { var a = document.getElementById("pre-tax").value; if (parseInt(a)>8000) { document.getElementById("interest").value =800+ (a - 8000)*15/100; } else { document.getElementById("interest").value =a/10; } } //为keyListener方法注册按键事件 document.onkeydown=keyListener; function keyListener(e){ // 当按下回车键,执行我们的代码 if(e.keyCode == 13){ calculate(); } } </script> </head> <body > 税前薪资:<input type="text" id="pre-tax"/> <input type="button" id="calculate" value="计算" onclick="calculate()"/> 利息:<input type="text" id="interest" readonly="readonly"/> </body> </html>
This small example is very simple and the code is easy to understand, but the things behind the code are not understandable by ordinary people. If you understand, please raise your hand....
I hope this article will be helpful to everyone’s JavaScript programming design.