简体   繁体   中英

jquery: select and unselect items of listbox

I have 2 listboxes (select, in HTML) in a ASP.NET page. I want that when one item of list1 is selected, the selected item in list2 is unselected, and viceversa.

The 2 selects are mutually exclusive.

How can I do?

$(function() {
    var list1 = $("#listbox1");
    var list2 = $("#listbox2");

    list1.change(function() {
        $("option", list2).attr('selected', false);
    });

    list2.change(function() {
        $("option", list1).attr('selected', false);
    });
});

Try with something like:

$(document).ready(function() {
    $("#listbox1").change(function() {
        if ($(this).val() != "")
            $("#listbox2 option:selected").attr("selected", "");
    });
    $("#listbox2").change(function() {
        if ($(this).val() != "")
            $("#listbox1 option:selected").attr("selected", "");
    });
});

I think Aaron's answer would work cross-browser, but in cases like this radio boxes should be used instead of check boxes...

Radio boxes were designed specifically for situations like these...

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