简体   繁体   中英

Disable certain options in a drop down select

Need to disable option "5" & "6" when the option value "2" is selected. It should display all the options in the List_2 when option "1" is selected. How can I do that using jQuery or any other method.

 if ($('option[value=2]').prop('selected', true)) { $('option[value=5]').prop('disabled', true); } 
 <HTML> <body> <select id= "List_1"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <select id= "List_2"> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> </select> </body> </HTML> 

Here you go with a solution https://jsfiddle.net/eurbvzk1/

 var disabledDic = { "1" : ["6"], "2" : ["4", "5"], "3" : [] } $('select#list_1').on('change', function(){ $('select#list_2 option').each(function(){ $(this).removeAttr('disabled'); }); var disableOption = disabledDic[$(this).val()]; $.each( disableOption, function(i){ $('option[value="' + disableOption[i] + '"]').prop('disabled', 'disabled'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="list_1"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 2</option> </select> <select id= "list_2"> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> </select> 

Create a dictionary that will contain each first select option as key & value will be list of disabled options from second list.

Onchange method check the dictionary & loop through the disabled value.

Hope this will help you.

With plain JS:

 document.getElementById('List_1').onchange = function() { document.getElementById('List_2')[1].disabled = (document.getElementById('List_1').selectedIndex == 1); document.getElementById('List_2')[2].disabled = (document.getElementById('List_1').selectedIndex == 1); } 
 <select id="List_1"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <select id="List_2"> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM