Reputation: 373
I have 2 selects, and I want to remove, based on the values from second select, values from first. For example: if I select value 1 and 2 from second select, I want that values 2,3,4,5 are hidden, and if in the second select value is 3, I want that values 1,2,3 are hidden:
Select1:
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Select2:
<select name="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
This is the code for hiding in the case that is selected 1 or 2:
var ary=[2,3,4,5];
$('[name=select1] option').filter(function(){
return ($.inArray(parseInt(this.value),ary) >-1);}).hide();
This code works for hiding, but I have a problem. When the code hides 2,3,4,5 on value 1 and 2, selecting value 3 in second select shows me only value 1, because others are hidden. I solved this using show(). And then 2,3,4,5 are showed but I can't hide value 1 because of the return :// I tried this, it won't work:
var ary=[4,5];
var ary2=[1];
$('[name=select1] option').filter(function(){
return ($.inArray(parseInt(this.value),ary) >-1);}).hide()&&($.inArray(parseInt(this.value),arry2) >-1);}).show();
I also tried to call another function which would always refresh select1 , showing it all values, and in this functions only to use hides, I think that wouldbe right way, but I don't know how to solve it?
Upvotes: 2
Views: 143
Reputation: 9167
Fiddle of this here: http://jsfiddle.net/8ZuGE/
Note, the adding list items I guess could be a bit more efficient here, but you get the idea:
var $resetValues = $('#select1').find("option");
$('#select2').on('change', function() {
var selected = $("option:selected", this).val();
// Reset select1
$('#select1').empty();
$resetValues.each(function() {
$('#select1').append($(this));
});
var array; // Hidden values
if(selected > 0 && selected < 3) {
array = [2,3,4,5];
} else {
array = [1,2,3];
}
$('#select1 option').filter(function() {
return ($.inArray(parseInt($(this).val()), array) != -1);
}).remove();
});
Upvotes: 1