简体   繁体   中英

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,
- second, be careful, your input will always be a string, you have to parseInt it in order to make a sum

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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