I have the following jQuery script:
$(document).ready(function() {
$.ajax({
url: 'temp.ajax.php',
type: 'GET',
success: function(data){
$("#total_plus_aditional").val(data);
}
});
tempTotal = parseFloat($("#total_plus_adi开发者_JAVA技巧tional").val());
$("#cost_valoare").change(function(){
var sum = parseFloat(tempTotal) + parseFloat($("#cost_valoare").val());
$("#total_plus_aditional").val(sum);
});
});
Now, here's what I want to do: the temp.ajax.php returns a float value. First, that float value is assigned to an input field in the html so the user can see the number. Then, if the user enters a number in another input field, I would like to make the sum of those two numbers and rewrite the value in the first input field.
The problem is that if I write a number in a second field, the content of the first field (with the float number returned by ajax call) turns to NaN.
Why is this happening?
P.S. I'm saving the value returned by the ajax call in a separate variable because I would like to have the same value if the user changes his mind and enters another value in the second field after he already entered one.
That line of code that initializes the global variable "tempTotal" almost certainly runs before your AJAX call returns from the server. Thus, it's a NaN because the field was empty when that ran.
Put that line of code in the "success" function and see what happens.
edit — wait — why are you calling parseFloat
twice on the same value? Don't do that. Really, the whole "tempTotal" thing is useless. Just have the "change" handler do this:
var sum = parseFloat($('#total_plus_aditional').val()) + parseFloat($("#cost_valoare").val());
If you really must save the value, do it in the AJAX response:
success: function(data){
$("#total_plus_aditional").val(data);
tempTotal = parseFloat(data);
}
and then don't call parseFloat on it again in the "change" handler.
精彩评论