I have multiple instances of select drop downs on a form, eight to be exact. If I select a number on the first select drop down I want to hide the selected number from the second select drop down up to eighth.
For the purpose of this I will only show two of the eight select drop downs.
View Code -
Select drop down one -
<div class="col-xs-12 col-sm-3">
<div class="form-group">
<?php echo Form::label('test_id', 'Test', array('class' => 'col-xs-3 control-label')) ?>
<div class="col-xs-9">
<select name="test_id" id="test_id" class="form-control select2" data-placeholder="Select...">
<option value=""></option>
<?php foreach (ORM::factory('Test')->order_by('id')->find_all() as $row) : ?>
<option value="<?php echo $row->id ?>"
<?php if ($b->id == $row->id) echo 'selected="selected"' ?>>
<?php echo $row->id ?></option>
<?php endforeach ?>
</select>
</div>
</div>
Select drop down two-
<div class="col-xs-12 col-sm-3">
<div class="form-group">
<?php echo Form::label('test_id', 'Test', array('class' => 'col-xs-3 control-label')) ?>
<div class="col-xs-9">
<select name="test_id" id="test_id" class="form-control select2" data-placeholder="Select...">
<option value=""></option>
<?php foreach (ORM::factory('Test')->order_by('id')->find_all() as $row) : ?>
<option value="<?php echo $row->id ?>"
<?php if ($b->id == $row->id) echo 'selected="selected"' ?>>
<?php echo $row->id ?></option>
<?php endforeach ?>
</select>
</div>
</div>
jQuery Code -
var $selects = $('select');
$('select').change(function () {
$('option:hidden', $selects).each(function () {
var self = this,
toShow = true;
$selects.not($(this).parent()).each(function () {
if (self.value == this.value) toShow = false;
})
if (toShow) $(this).show();
});
if (this.value != "") //to keep default option available
$selects.not(this).children('option[value=' + this.value + ']').hide();
});
This does not work in the slightest.
Any help would be appreciated.
Cheers
This won't work with select2 and hidden options. You can work around this by disabling the options and a bit of CSS to hide them. See below:
JS
$(document).ready(function () {
var $selects = $('select');
$selects.select2();
$('select').change(function () {
$('option:hidden', $selects).each(function () {
var self = this,
toShow = true;
$selects.not($(this).parent()).each(function () {
if (self.value == this.value) toShow = false;
})
if (toShow) {
$(this).removeAttr('disabled');
$(this).parent().select2();
}
});
if (this.value != "") {
$selects.not(this).children('option[value=' + this.value + ']').attr('disabled', 'disabled');
$selects.select2();
}
});
})
CSS
.select2-results .select2-disabled {
display:none;
}
Working example here: http://jsfiddle.net/10nwqwck/4/