How do I enable/disable options in Select Box using jquery

被刻印的时光 ゝ 提交于 2019-12-19 13:10:11

问题


I have a select box which contains the options and optgroup that are generated dynamically using php.Now when I select "ALL" all the other optgroup, options should be disabled and when I select any option other than "ALL" the "ALL" option should be disabled

<select name="select1" id ="select1" onchange="handleSelect()">
    <option value ="-1">ALL</option>
    <optgroup label="CARS">
        <option value="ford">FORD</option>
        <option value="Nissan">Nissan</option>
    </optgroup>
</select>
<script>
    function handleSelect() {
        var selectVal = $("#select1:selected").text();
        if (selectVal == "ALL") {
            // cannot disable all the options in select box
            $("#select1  option").attr("disabled", "disabled");
        }
        else {
            $("#select1 option[value='-1']").attr('disabled', 'disabled');
            $("#select1 option").attr('disabled', '');
        }
    }
</script>

How can I make this working?


回答1:


This is kind of a strange thing to be doing but here's code that meets your requirements.

$('select').on('change', function() {
    if (this.value == '-1') {
        $('optgroup option').prop('disabled', true);
    } else {
        $('optgroup option').prop('disabled', false);
    }
});

Live Example - http://jsfiddle.net/NpNFh/




回答2:


You can use the following code.Let us consider you have three select boxes as follows

<select class="sel_box" id="sel_1" onchange="disable_sel(this.value);" ></select>
<select class="sel_box" id="sel_2" onchange="disable_sel(this.value);" ></select>
<select class="sel_box" id="sel_3" onchange="disable_sel(this.value);" ></select>

and in function let 'opt' is argument now use following

$('.sel_box option[value="'+opt+'"]').attr("disabled", true);



回答3:


You can use two variations on the syntax for the disabled attribute, depending on the version of HTML you are targeting:

HTML4: <option value="spider" disabled>Spider</option>
XHTML: <option value="spider" disabled="disabled">Spider</option>


来源:https://stackoverflow.com/questions/10953589/how-do-i-enable-disable-options-in-select-box-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!