简体   繁体   English

如何使用javascript同时触发回车键和按钮

[英]How to trigger enter key and button in the same time using javascript

Please help me to understand how to trigger enter key and button in the same time.请帮助我了解如何同时触发输入键和按钮。 Value in the input has to trigger same on press enter key and on button "Enter" in the same time in this code.在此代码中,输入中的值必须同时在按下回车键和“回车”按钮时触发。 And after pressing the button, input field will clears each time.并且每次按下按钮后,输入字段都会被清除。

 <div id="myForm"> <input type="text" id="bedrag" /> <button type="button" onclick="check_field('bedrag');" value=''>Enter</button> <p>Uw totaal:</p> <p id="resultaat"></p> </div> <script> var totaal = 0; var bedrag = document.getElementById("bedrag"); bedrag.onkeydown = bereken function bereken(e) { if (e.keyCode == 13) { var ingevoerdeBedrag = +document.getElementById("bedrag").value; totaal = totaal + ingevoerdeBedrag; document.getElementById("resultaat").innerHTML = 'Het bedrag is ' + totaal; } } function check_field(id) { var field = document.getElementById(id); if (isNaN(field.value)) { alert('not a number'); } else { return myFunction(); } } </script>

Two things:两件事情:
- first, find out common code to run both on clicking the button and pressing the Enter key, then put it into a single function, - 首先,找出在单击按钮和按 Enter 键时运行的通用代码,然后将其放入单个 function 中,
- second, be careful, your input will always be a string, you have to parseInt it in order to make a sum - 第二,要小心,你的输入总是一个字符串,你必须parseInt它才能求和

Here is a working example:这是一个工作示例:

 <div id="myForm"> <input type="text" id="bedrag" /> <button type="button" onclick="check_field('bedrag');" value=''>Enter</button> <p>Uw totaal:</p> <p id="resultaat"></p> </div> <script> var totaal = 0; var bedrag = document.getElementById("bedrag"); bedrag.onkeydown = bereken function submit() { var ingevoerdeBedrag = document.getElementById("bedrag").value; if (isNaN(parseInt(ingevoerdeBedrag))) { alert('not a number'); } else { totaal = totaal + parseInt(ingevoerdeBedrag); document.getElementById("resultaat").innerHTML = 'Het bedrag is ' + totaal; } } function bereken(e) { if (e.keyCode == 13) { submit(); } } function check_field(id) { submit(); // Here we're clearing the input only after clicking the button document.getElementById(id).value = ""; } </script>

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

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