How to disable previous selected options when choosing an option from the first choice

I have two select elements. both options have the same meaning. when I select an option from selection window 1, it should disable all previous selection options from the second selection window. Suppose I have this choice:

<select id="s1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <select id="s2"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> 

If I select 3 from the s1 window, it should disable all previous options from the s2 selection. if I select value 2 from s1, it should disable all previous values ​​in s2.

Note It should not disable the following values, only the previous ones. I am looking for a jquery solution.

+5
source share
2 answers

Use :lt to select items with a lower index than specified.

.index() will return the position of the element from the matched element.

.not() excludes the specified item from the returned items.

 $('select').change(function() { $('select option').prop('disabled', false); var index = $(this).find('option:selected').index(); $('select').not(this).find('option:lt(' + index + ')').prop('disabled', true); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <select id="s1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <select id="s2"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> 

Script here

+7
source

Try it under code. If this is useful to you.

 $(document).ready(function() { $("#s1").change(function() { var optVal = $(this).val(); $("#s2 option").each(function() { $(this).prop('disabled', false); if (optVal > $(this).val()) { $(this).prop('disabled', true); } }); });}); 
0
source

Source: https://habr.com/ru/post/1244790/


All Articles