Reputation: 5757
I have a form that has 10 or so dropdown menus. Two of these dropdowns, are different from the others, and I'm trying to figure out how to not let the user have the same value in each of these dropdowns.
For example,
<select id="z_one">
<option>1</option>
<option>1</option>
<option>1</option>
</select>
<select id="z_two">
<option>1</option>
<option>1</option>
<option>1</option>
</select>
Is there a way to iterate through only these two selects, and not the others, and check for matching values?
$('select[id^=z_]').change(function() {
var value = $(this);
$(this).siblings().each(function() { //this checks all siblings. do not want.
if ($(this).val() == value.val()) {
alert("You can't select the same value twice.");
return false;
}
});
});
This jquery code iterates through all selects on the page, instead of just the two I want to check against. Is there a way to do this?
Upvotes: 0
Views: 195
Reputation: 2860
I have changed your html a little.
<select id="z_one" class='groupA'>
<option>Select an element</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="z_two" class="groupA">
<option>Select an element</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Here is the JS code :
$(function(){
$('.groupA').change(function(){
var currentID = this.id;
var currentVal = $(this).val();
var $options = $('option','.groupA');
var $jThis = $(this);
var isMatched = false;
$.each($options,function(index,element){
if(element.parentNode.id != currentID ){
var $prevDropDown = $('#' + element.parentNode.id);
if($prevDropDown.val() == currentVal){
$jThis.get(0).selectedIndex = 0;
alert("You can't select the same value twice.");
isMatched = true;
return false; // to break out from $.each
}
}
});
if(isMatched)
return false;
});
});
Upvotes: 0
Reputation: 1355
Try some sort of predicate on your call to siblings to limit it to just those two selects.
Something like
this.siblings("[id = 'z_two']")
for example.
Upvotes: 1
Reputation: 87073
Instead of
$(this).siblings().each(
use
$(this).next('select[id^=z_]').each(
Upvotes: 1