How do I add Text before my answer in the text box using setAttribute but only after the resullt has been printed

I want it to read the-number-that-has-been-computed) where the-number-that-has-been-computed is the result of the addition of the first two text boxes( I am also using window.onload that is why my script is in the head of the file.

function setUpEvents() {
  function add_number() {
    var first_number = parseInt(document.getElementById("tb1").value);
    var second_number = parseInt(document.getElementById("tb2").value);
    var result = first_number + second_number;
    document.getElementById("tb3").value = result;
  };
}
window.onload = function() {
  setUpEvents();
};
<div>
  <h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1">
<br> Enter Second Number : <br>
<input type="text" id="tb2" name="TextBox2">
<br> Result : <br>
<input type="text" id="tb3" name="TextBox3">
<br>
<input type="button" name="b1" value="GO" onclick="add_number()">

29 thoughts on “How do I add Text before my answer in the text box using setAttribute but only after the resullt has been printed”

  1. Welcome to SO!

    if i were you id set up a button that, once pressed, will action add_number();
    remove it from "set up events", make it a function on its own, thats called once the button is pressed.

    your button could look like this:

    <input type=submit onclick="add_number()" />
    

    and your JS code could look like this :

     function add_number() {
        var first_number = parseInt(document.getElementById("tb1").value);
        var second_number = parseInt(document.getElementById("tb2").value);
        var result = first_number + second_number;
        document.getElementById("tb3").value = result;
      };
    
    Reply
  2. Just remove the setUpEvents to not have the function out of scope for the inline event handler

    Also remove the inline event handler

    Use eventListeners instead. I changed the name to id for the button

    function add_number() {
      var first_number = parseInt(document.getElementById("tb1").value);
      var second_number = parseInt(document.getElementById("tb2").value);
      var result = first_number + second_number;
      document.getElementById("tb3").value = "The-number-that-has-been-computed is "+ result;
    };
    window.addEventListener("load", function() {
      document.getElementById("b1").addEventListener("click", add_number);
    });
    input { width: 300px }
    <div>
      <h1>Add two number using text box as input using javascript</h1>
    </div>
    Enter First Number : <br>
    <input type="text" id="tb1" name="TextBox1">
    <br> Enter Second Number : <br>
    <input type="text" id="tb2" name="TextBox2">
    <br> Result : <br>
    <input type="text" id="tb3" name="TextBox3">
    <br>
    <input type="button" id="b1" value="GO" />
    Reply

Leave a Comment