user2906420
user2906420

Reputation: 1269

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?

Upvotes: 0

Views: 2541

Answers (1)

Satpal
Satpal

Reputation: 133403

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

Upvotes: 3

Related Questions