Dayley
Dayley

Reputation: 301

Using Javascript's getElementsByName and outputting a result using getElementById

I am having trouble grabbing multiple input's using the inputs name and adding multiplications to them like below. Is there another way I can do this without using getElementById ?

<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">

<button onclick="GetTheResults()">Try it</button>

<p id="demo">Click the button to change the text in this paragraph.</p>

<script>
x = document.getElementsByName("test1").value;
z = document.getElementsByName("test2").value;
var Savings = x + z;
function GetTheResults() {
document.getElementById("demo").innerHTML = Savings;
}
</script>

Please note I have also tried the following:

x = document.getElementsByName("test1")[0].value;
z = document.getElementsByName("test2")[0].value;

Upvotes: 0

Views: 251

Answers (2)

SaschaM78
SaschaM78

Reputation: 4497

You need to move the document.getElementsByName() calls into the function. You will also need to use parseInt() to convert the inputs into integer values. As the name getElementsByName implies, the returned value is an array of all found elements; in your case you will need to access the first element of the returned array for your addition.

Code

function GetTheResults() {
  x = parseInt(document.getElementsByName("test1")[0].value);
  z = parseInt(document.getElementsByName("test2")[0].value);
  var Savings = x + z;

  document.getElementById("demo").innerHTML = Savings;
}
<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">
<button onclick="GetTheResults()">Try it</button>
<p id="demo">Click the button to change the text in this paragraph.</p>

Upvotes: 1

Nitin Goyal
Nitin Goyal

Reputation: 507

<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">

<button onclick="GetTheResults()">Try it</button>

<p id="demo">Click the button to change the text in this paragraph.</p>

<script>
    function GetTheResults() {
        x = document.getElementsByName("test1")[0].value;
        // x = document.getElementById("RoundInput1").value;

        z = document.getElementsByName("test2")[0].value;
        // z = document.getElementById("RoundInput2").value;

        var Savings = parseInt(x) + parseInt(z);
        document.getElementById("demo").innerHTML = Savings;
    }
</script>

Upvotes: 2

Related Questions