Event handler for unselection of an Item in select

2019-06-04 21:57发布

问题:

I am using a select menu which will allow multiple selections to be done. I have an event handler

 $("#idInventory").change(function () {
     $("#select option:selected").each(function () {
    });
});

which is called when an item is selected. Here I collect what ever items are chosen . But I also need to know when each selected item is deselected so that I can track what is deselected so that I can keep track if something already chosen is now deselected by user.

UPDATE: I am not getting this event triggered when an item is deselected.

回答1:

I think this is what you might be looking for:

  • How to fetch all the option values(selected/unselected) in a selectbox

Kinda working demo:

  • http://jsfiddle.net/5hpU2/9/

HTML

<div data-role="page" data-theme="b" id="home"> 
    <div data-role="content">

        <div data-role="fieldcontain"> 
            <label for="select-choice-9" class="select">Choose shipping method(s):</label> 
            <select name="select-choice-9" id="select-choice-9" multiple="multiple" data-native-menu="false"> 
                <option>Choose options</option> 
                <option value="standard">Standard: 7 day</option> 
                <option value="rush">Rush: 3 days</option> 
                <option value="express">Express: next day</option> 
                <option value="overnight">Overnight</option> 
            </select> 
        </div>

    </div>
</div>

JS

var values = {
    selected: [],
    unselected:[]
};

$("#select-choice-9").change(function () {
    values.selected   = [];
    values.unselected = [];

    $("#select-choice-9 option").each(function(){
        values[this.selected ? 'selected' : 'unselected'].push(this.value);
    });

    alert('Selected: '+values.selected+' Unselected: '+values.unselected);
});

UPDATE:

$("#select-choice-9").change(function () {
    values.selected   = [];
    values.unselected = [];

    $("#select-choice-9 option").each(function(){
        values[this.selected ? 'selected' : 'unselected'].push(this.value);
    });

    alert('Selected: '+values.selected+' Unselected: '+values.unselected);
}).page();

UPDATE #2

$("#select-choice-9").change(function () {
    values.selected   = [];
    values.unselected = [];

    $("#select-choice-9 option").each(function(){
        values[this.selected ? 'selected' : 'unselected'].push(this.value);
    });

    alert('Selected: '+values.selected+' Unselected: '+values.unselected);
}).checkboxradio("refresh");


回答2:

$("option").click(function(){
    if(this.selected)
      //do what you want to do
});