Reputation: 1040
Based on this http://api.jquery.com/val/ trying to create code (get values from 2 input fields, multiply and insert result in third input field).
Placed sample here http://jsfiddle.net/KWEyG/1/
<td><input type="text" name="result[]" id='result' value="77"></td>
<td><input type="text" name="firstVal[]" id='firstVal' value="first"></td>
<td><input type="text" name="secondVal[]" id='secondVal' value="second"></td>
And then jquery
function displayVals() {
var firstValue = $("#firstVal").val();
var secondValue = $("#secondVal").val();
$("#result").val(firstValue*secondValue);
}
$("input").change(displayVals);
displayVals();
Default value for result
is 77
. But with the code default value see NaN
.
Added if ( ($("#firstVal").val() > 0) && ($("#secondVal").val() != '') ) {
. Default value is ok, but no calculations.
What need to correct to get the script work?
Update
Based on advices get what is necessary
function displayVals() {
if ( ($("#firstVal").val() > 0) && ($("#secondVal").val() != '') ) {
var firstValue = $("#firstVal").val();
var secondValue = $("#secondVal").val();
$("#result").val(firstValue*secondValue);
}
$("input").change(displayVals);
}
displayVals();
Upvotes: 0
Views: 1977
Reputation: 1700
You were multiplying strings instead use integer values like below:
<td><input type="text" name="result[]" id='result' value="77"></td>
<td><input type="text" name="firstVal[]" id='firstVal' value=""></td>
<td><input type="text" name="secondVal[]" id='secondVal' value=""></td>
Edit:
$("#check").click(function(){
if ( ($("#firstVal").val() > 0) && ($("#secondVal").val() != '') ) {
displayVals();
}else{
alert("insert a value");
}
})
Working Fiddle
Upvotes: 0
Reputation: 3481
See your code:
You are multiplying a String
with String
which is a obvious result NaN
Second thing to understand is use parseInt
or parseFloat
before arithmetic calculation and then check for by isNaN
method.
$("#firstVal").val();
will result in attribute value of value
in element <input>
and here that is first
(String
).
Check by using alert:
function displayVals() {
var firstValue = $("#firstVal").val();
var secondValue = $("#secondVal").val();
alert(firstValue+' '+secondValue+(firstValue*secondValue));
}
But when you change both value to number
it should work as value
will be a number.
Upvotes: 1
Reputation: 1527
The NaN
is inserted into #result
because you call displayVals();
at the end of your code-snippet. The function now tries to multiply first
and second
which of course returns NaN
since you can't multiply strings.
Upvotes: 0