Reputation: 327
I have this jquery function:
$(function() {
$('.submitButton').click(function(){
$('input').each(function() {
if ($(this).attr('min')) {
if ($(this).val()<$(this).attr('min')){
$('#'+$(this).attr('id')+"_errMess").prepend(' Your data should be more than '+$(this).attr('min'));
}
}
});
});
});
It seems that it checks only the first digit entered in the input. because for example when the value of 'min' attribute is 7, and the value entered in input is 10, it shows the error message (the if condition is true!!). although when i want it to alert value, it seems it knows the true and total value and returns 10.
alert($(this).val());
Can you please help me understand what is wrong?
Upvotes: 0
Views: 77
Reputation: 10224
val()
returns string and string "10" IS less than "7" in JavaScript. What you actually need is number comparison, so converting them by parseInt
or Number
before comparing the strings. You may check the other question on stackoverflow: Why is string "11" less than string "3"? .
By the way, you'd better save the $(this) to a variable instead of calling dollar function repeatedly.
Upvotes: 1
Reputation: 2883
The issue here is it is comparing '7' to '10' and not 7 to 10 [ASCII comparison character by character and not actual integer comparison]. Do parseInt() to the values and then compare, you should get desired results.
Change
$(this).val()<$(this).attr('min')
to
parseInt($(this).val())< parseInt($(this).attr('min'))
inside your if condition
ALso its better to extract the values to the variable and then perform the comparison.
Upvotes: 1
Reputation: 5265
You're missing the cast from string (.val
returns string) to numeric:
$(function() {
$('.submitButton').click(function() {
$('input').each(function() {
if ($(this).attr('min')) {
if (Number($(this).val()) < Number($(this).attr('min'))) {
$('#' + $(this).attr('id') + "_errMess").prepend(' Your data should be more than ' + $(this).attr('min'));
}
}
});
});
Upvotes: 1