Anna Daviduk
Anna Daviduk

Reputation: 15

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>

Upvotes: 0

Views: 412

Answers (1)

giuseppedeponte
giuseppedeponte

Reputation: 2381

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>

Upvotes: 1

Related Questions