Disable selected item and below in another select
I have two drop down lists. I need to disable items that I choose from the first select and the items below it. How can I do it in jQuery? I could disable the same value, but not the values below. Can any body help?
$('#seat').on('change', '.from select', function() {
$('option[disabled]').prop('disabled', false);
$('.station_from').each(function() {
$('.stationTo').not(this).find('option[value="' + this.value + '"]').prop('disabled', true);
});
});
Solution 1:
You can do a loop check. this is not the most efficient way but its a simple one. You can read the comments in the code to better understand it
// When the value for the first drop down list changes
$('#firstSelect').change(function() {
// get the selected value of the first drop down list
var selectedValue = $(this).val();
// we need this flag to check if we have reached the selected value in the second drop down list. we default it to false since we have not found it yet
var foundOption = false;
//for each option in the second drop down list
$("#secondSelect option").each(function(key,value){
// enable that option
$(value).prop('disabled', false);
// check if the option in the second drop down list has the same value as the selected value of the first drop down list
if($(value).val() == selectedValue){
// if so then set flag to true
foundOption = true;
}
// if flag is true or in other words if we have found the option in the second drop down list with the same selected value of the first drop down list
if(foundOption){
// then disable that option and every option that comes after that value
$(value).prop('disabled', true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstSelect">
<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>
<br>
<br>
<br>
<select id="secondSelect">
<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>
<option value="6">6</option>
<option value="7">7</option>
</select>