I\'ve tried use Plus Arithmetic Operation to calculate 2 input text type number values, but my result was the values are \"together\", like that:
http://jsfiddle.net/BLGLe/
<script type="text/javascript">
function cal(){
var plus = parseInt(document.getElementById('plus').value),
plus1 = parseInt(document.getElementById('plus1').value);
var x = plus + plus1;
var result = document.getElementById('result');
if(result.value == ""){
result.innerHTML = "?";
}
else{
result.innerHTML = x;
}
}
</script>
<input type="text" id="plus" /> + <input type="text" id="plus1" /> = <span id="result"></span>
You can try this:
function cal(){
var plus = +document.getElementById('plus').value,
plus1 = +document.getElementById('plus1').value;
var x = plus + plus1;
var result = document.getElementById('result');
if(isNaN(plus) || isNaN(plus1) || result.value == ""){
result.innerHTML = "?";
}
else{
result.innerHTML = x;
}
}
Notice the + signs that convert the two string values to numbers.
parseInt is what missing from your code .. you need to parse it as integer barring which just the concatenation operation takes place , so you can either do this
var plus = parseInt(document.getElementById('plus').value, 10),
plus1 = parseInt(document.getElementById('plus1' ).value, 10);
or
var x = parseInt(plus , 10) + parseInt(plus1 , 10) ;
You need to parse them to an Integer type:
var x = parseInt(plus) + parseInt(plus1);
Then you can use isNaN() to determine whether it was a valid operation or not: (note that I'm checking the value of x
not of the resulting output)
if(isNaN(x)){
result.innerHTML = "?";
}
else{
result.innerHTML = x;
}
Living demo: http://jsfiddle.net/4KB5Y/3/
All values you get from input elements in the DOM are going to be strings.
Javascript uses +
both for concatenating strings and for addition.
To make it clear you want to add numbers instead of concatenating strings, you need to make sure your values are numbers:
parseInt(plus, 10) + parseInt(plus1, 10)
Yes, this is one of the most basic and often encountered gotchas in Javascript.
var plus = parseInt(document.getElementById('plus').value, 10),
plus1 = parseInt(document.getElementById('plus1').value, 10);
This will do what you want.