Reputation: 61
I have 2 html input fields, one in disabled and gets value from a php file using jQuery ajax and the other one is filled by the user.
I made a jQuery script which compares these two fields and should show a message if the user input is greater than the ajax filled input. The problem is that it returns a strange result, for example if the ajax field is 12300 and the input field is 8 it shows the message, but if ajax is 12300 and the input is 12229 than it does not show the message.
$(document).ready(function(){
$("#cantitate").blur(function(){
var cant_ins = $("#cantitate").val();
var cant_suger = $("#info_cantitate").val();
if (cant_ins > cant_suger){
$("#status_cant").text("Cantitatea depaseste disponibilitatea");
}
else
{
$("#status_cant").empty();
}
});
});
Upvotes: 0
Views: 76
Reputation: 318202
You're comparing strings, not numbers, that's why you get strange results, 1200
would be less than 200
as the first one starts with the character 1
and the second one with 2
etc.
You can use parseInt
for integers or parseFloat
for floats to parse the strings as numbers, or you can just use the +
sign to coerce the strings to numbers
$(document).ready(function(){
$("#cantitate").on('blur', function(){
var cant_ins = +$("#cantitate").val();
var cant_suger = +$("#info_cantitate").val();
if (cant_ins > cant_suger){
$("#status_cant").text("Cantitatea depaseste disponibilitatea");
} else {
$("#status_cant").empty();
}
});
});
Upvotes: 3