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

请帮助我了解如何同时触发回车键和按钮。在此代码中,输入中的值必须在同时按下回车键和“回车”按钮时触发相同的值。每次按下按钮后,输入字段都会清除。


<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>


梵蒂冈之花
浏览 218回答 1
1回答

哆啦的时光机

两件事:-首先,找出在单击按钮和按 Enter 键时运行的通用代码,然后将其放入单个函数中,-其次,请注意,您的输入将始终是一个字符串,您必须将parseInt其输入求和这是一个工作示例:<div id="myForm">&nbsp; <input type="text" id="bedrag" />&nbsp; <button type="button" onclick="check_field('bedrag');" value=''>Enter</button>&nbsp; <p>Uw totaal:</p>&nbsp; <p id="resultaat"></p></div><script>&nbsp; var totaal = 0;&nbsp; var bedrag = document.getElementById("bedrag");&nbsp; bedrag.onkeydown = bereken&nbsp; function submit() {&nbsp; &nbsp; var ingevoerdeBedrag = document.getElementById("bedrag").value;&nbsp; &nbsp; if (isNaN(parseInt(ingevoerdeBedrag))) {&nbsp; &nbsp; &nbsp; alert('not a number');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; totaal = totaal + parseInt(ingevoerdeBedrag);&nbsp; &nbsp; &nbsp; document.getElementById("resultaat").innerHTML = 'Het bedrag is ' + totaal;&nbsp; &nbsp; }&nbsp; }&nbsp; function bereken(e) {&nbsp; &nbsp; if (e.keyCode == 13) {&nbsp; &nbsp; &nbsp; submit();&nbsp; &nbsp; }&nbsp; }&nbsp; function check_field(id) {&nbsp; &nbsp; submit();&nbsp; &nbsp; // Here we're clearing the input only after clicking the button&nbsp; &nbsp; document.getElementById(id).value = "";&nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript