Raios
Raios

Reputation: 65

How to Basically Add the Values of Two <Button> tags

I think I got the logic part right, another problem I have is the NaN output that I keep receiving when I click on the <button> tags. I did use addEventListener('click') method but it seems more complicated, so I tried this simple codes instead. I'm just having trouble on how to add the values of the buttons, any help would be appreciated.

Here's my code :

<html>


<body>

<script type = "text/javascript">

 function test(value)
{
    var val = parseFloat(value);
    var total = parseInt(document.getElementById('totaltext').value);

    document.getElementById('totaltext').innerHTML =  total + val;
} 

</script>


total : <p id = "totaltext" value = "0">0</p>
<button value = "10.11" name = "product" id = "button1" onClick = "test(this.value);">value1</button>


<button value = "20.00" name = "product" id = "button2" onClick = "test(this.value);">value2</button>



</body>
</html>

https://jsfiddle.net/7tm161ob/1/

Upvotes: 1

Views: 322

Answers (1)

Ibu
Ibu

Reputation: 43820

Because the elements you are accessing button is not an input tag, the value attribute is not the correct one. value is considered an html attribute in this case that is not directly available in the JavaScript object.

You will need to use the method .getAttribute() to get those values. Here is how it works.

<button value="10.11" name="product" id="button1" onclick="test(this);">value1</button>

<button value="20.00" name="product" id="button2" onclick="test(this);">value2</button>

function test(button) {
    var val = parseFloat(button.getAttribute("value"));
    var total = parseFloat(document.getElementById('totaltext').getAttribute("value"));

    document.getElementById('totaltext').innerHTML =  total + val;
    document.getElementById('totaltext').setAttribute("value",total + val)
} 

Working Example

Upvotes: 3

Related Questions