i have the following script
<select id="select1">
<option value="1">1day</option>
<option value="2">2day</option>
<option value="3">3day</option>
</select>
<select id="select2">
<option value="1">1day</option>
<option value="2">2day</option>
<option value="3">3day</option>
</select>
and jquery
$("#select2").change(function() {
var max_value = parseInt($("#select2 :selected").val());
var min_value = parseInt($("#select1 :selected").val());
if(max_value < min_value)
{
$("#select1").val($(this).val());
}
});
and now, what i can't understand anyway - if values of option elements are integer numbers, why i have to use parseInt()? in some cases it doesn't work without parseInt().
Thanks
i have the following script
<select id="select1">
<option value="1">1day</option>
<option value="2">2day</option>
<option value="3">3day</option>
</select>
<select id="select2">
<option value="1">1day</option>
<option value="2">2day</option>
<option value="3">3day</option>
</select>
and jquery
$("#select2").change(function() {
var max_value = parseInt($("#select2 :selected").val());
var min_value = parseInt($("#select1 :selected").val());
if(max_value < min_value)
{
$("#select1").val($(this).val());
}
});
and now, what i can't understand anyway - if values of option elements are integer numbers, why i have to use parseInt()? in some cases it doesn't work without parseInt().
Thanks
Share Improve this question asked May 29, 2010 at 18:34 SimonSimon 23.1k36 gold badges93 silver badges122 bronze badges 3-
1
Incidentally, you don't have to use
parseInt
here.+
will do as good a job, e.g.var max_value = +$("#select2 :selected").val();
. – Andy E Commented May 29, 2010 at 18:51 - @Andy E's head - ...O_O. I never knew that trick! I can't decide if that looks prettier or uglier than an explicit conversion... but I'll probably go for it when I deal with a variable name or an object property rather than a method call. – Matchu Commented May 29, 2010 at 18:54
- @Matchu: it's one of my favourite things about JS, saving all those bytes ;-) – Andy E Commented May 30, 2010 at 10:12
4 Answers
Reset to default 5Form field values are always stored as strings. Whether or not they look like integers is irrelevant; they're strings. You need to convert them to integers before treating them as such :)
http://www.uvsc.edu/disted/decourses/mct/2760/IN/krutscjo/lessons/06/ff_05.html
Javascript treats most everything as a string unless you explicitly tell it that it is a number. One notable example of this is getting values from form elements. Depending on the browser and user input you may get some unexpected results.
Values are never integers as such, the fact that you put numbers there instead of who-knows-what is your choice only.
jQuery's val() function always returns a string. In many cases you can mix numbers and strings (in arithmic for example), when paring two string variables, javascript will perform a string parison, not a numeric parison (which is to be expected)