简体   繁体   中英

JQuery Chosen plugin - get ID of selected option

I am using the Chosen plugin in MVC razor and need to get the selected item id in onchange event:

<optgroup label="@col">
    foreach (String[] colSub in sList)
        {                                            
           <option id="@colSub[1]" class="opts">@colSub[0]</option> 
        }
</optgroup>

JQuery:

$('#chosen').on('change', function (evt, params) {
     var selectedOption = params.selected; //gives me the selectedOption = @colSub[0]
     var id = //i need the id here  
}

In the above i need the ID also?

You can simply use

 $('#chosen').on('change', function (evt, params) { var id = $(this).find('option:selected').prop('id'); }); 

You can use use .map() to generate array of selected IDs

$("#chosen").on('change', function (evt, params) {
    var SelectedIds = $(this).find('option:selected').map(function () {
        return $(this).prop('id')
    }).get();
    console.log(SelectedIds);
})

DEMO

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