I
am, admittedly, fairly noobtastic at Javascript. So this post may be
common knowledge to most of you. That said, I encountered a strange
issue recently while comparing two selected values.
A
basic example of my two form fields:
<select
name="minimum"
id="min"
onchange="checkMin('min','max');">
<option
value=1>1</option>
<option
value=2>2</option>
<option
value=3>3</option>
...
<option
value=10>10</option>
<option
value=11>11</option>
(and
so on)
</select>
<select
name="maximum"
id="max"
onchange="checkMin('min','max');">
<option
value=1>1</option>
<option
value=2>2</option>
<option
value=3>3</option>
...
<option
value=10>10</option>
<option
value=11>11</option>
(and
so on)
</select>
The
idea was to make sure that on any change in these two selects, the
minimum value could not be greater than the maximum. Seemed simple
enough at first.
<script
type="text/javascript">
function
checkMin(minId,maxId) {
var
minObj =
document.getElementById(minId);
var
maxObj =
document.getElementById(maxId);
var
minValue =
minObj[minObj.selectedIndex].value;
var
maxValue =
maxObj[maxObj.selectedIndex].value;
if
(minValue >
maxValue) {
maxObj.selectedIndex
=
minObj.selectedIndex;
alert('can't
do that!');
}
}
</script>
That
method worked fine but only some of the time. Any guesses yet?
I
eventually realized the pattern that was forming...minValue could =
5, maxValue = 6 that worked fine. But, change the maxValue to 10 and
my condition would fire off the value change.
What
was happening? The values were being treated as strings instead of
numeric.
What
was the fix? Multiplying the values by 1.
var
minValue =
minObj[minObj.selectedIndex].value
*
1;
var
maxValue =
maxObj[maxObj.selectedIndex].value
*
1;
Once
I made those changes, everything worked just as expected.
Loading....