0

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>

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but now i have troubles how to clear the input field each time I press button "Enter". I have tried to add value='' to the button code, But it doesn't work anyway.
I have edited my code to show one way to clear the button after clicking the button

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.