Skip to content Skip to sidebar Skip to footer

Html Javascript Function Issue. [object Htmlinputelement] Error Output

I am trying to make a simple html page with two text boxes and an a button that adds the two numbers together when clicked. In my output, I am only getting [object HTMLInputElement

Solution 1:

I assume you want the mathematical sum and not the string concatenation. If that's the case, you can use the following:

UPDATE based on comment:

functionaddNumbers(elem1, elem2) {
  var a = document.getElementById(elem1).value;
  var b = document.getElementById(elem2).value;
  var c = Number(a) + Number(b);
  document.getElementById("testResult").innerHTML = c;
}
<inputtype="text"value="15"id="varA"><inputtype="text"value="30"id="varB"><inputtype="button"value="Add"onclick="addNumbers('varA', 'varB')"></input><h1id="testResult"></h1>

Here's a working Fiddle: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/.

Solution 2:

Some fixes:

  • You are adding up the inputs elements instead of their value.
  • To convert its string value to a number, you can use unary +.
  • Instead of inline event listeners, better use addEventListener.

var a = document.getElementById('varA'),
    b = document.getElementById('varB'),
    result = document.getElementById("testResult");

document.getElementById('add').addEventListener('click', function() {
  addNumbers(a.value, b.value);
});

functionaddNumbers(n1, n2){
  result.textContent = +n1 + +n2;
}
<inputtype="text"value="15"id="varA"><inputtype="text"value="30"id="varB"><inputtype="button"id="add"value="Add"><h1id="testResult"></h1>

Post a Comment for "Html Javascript Function Issue. [object Htmlinputelement] Error Output"