Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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:

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

    document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}

Solution 2:

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.

Solution 3:

You need to access the "value" property of the input fields and parse them as integers:

var value1 = parseInt(document.getElementById('value1').value);
var value2 = parseInt(document.getElementById('value2').value);

Solution 4:

You only read the values once, you should read them in the output function; You need to parse them to integers as well since 1+4 will become 14 if you use strings. Could be better but this should work.

<scripttype="text/javascript"language="javascript"charset="utf-8">functionoutput(){
    var value1 = parseInt(document.getElementById('value1').value);
    var value2 = parseInt(document.getElementById('value2').value);
    document.getElementById('result').innerHTML = value1 + value2;
}

</script>

Solution 5:

For completeness: your scripting could be better. Based on your form I cooked up another jsfiddle example.

Post a Comment for "Basic Javascript Math Text Field"