Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Javascript math text field

hello im new and learning javascript.

I'm trying to make a program of addition through text field.

Check the html code on js fiddle http://jsfiddle.net/fCXMt/

What I need to know is how can I accept user input in text field and diplay output in P tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>untitled</title>
</head>
<body>
<input id="value1" type="text" />
<span> + </span>
<input id="value2" type="text" />
<input type="submit" onclick="output();">
<p id="result"> </p>

<script type="text/javascript" language="javascript" charset="utf-8">
var value1 = document.getElementById('value1').innerHTML;
var value2 = document.getElementById('value2').innerHTML;

function output(){
    document.getElementById('result').innerHTML = value1 + value2;
}

</script>
</body>
</html>
like image 906
kevvvin Avatar asked Feb 24 '23 20:02

kevvvin


2 Answers

You have to grab the values in input fields after the button click, and use the value property (not innerHTML) to do it. Also, make sure you're adding numbers and not appending strings together. Try this:

function output(){
    var value1 = document.getElementById('value1').value;
    var value2 = document.getElementById('value2').value;

    document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}
like image 132
Kon Avatar answered Feb 26 '23 22:02

Kon


The property for getting the value of a textbox is value, not innerHTML, so change those, and you will also need to use eval or parseInt on the textbox values, otherwise it will concatenate them as strings.

Also, you need to move your variable declarations inside the function, so that when the function is called, the current values from the textboxes are retreived.

See update fiddle here.

like image 44
James Allardice Avatar answered Feb 26 '23 23:02

James Allardice