How to access the optgroup value in bootstrapselect onChange event

2.9k views Asked by At

i am using a bootstrap-select item in a form and i' d like to get the optgroup value for the selected value when it gets selectet, so i can evaluate what to do based on that groups value:

$('select.selectpicker').on('change', function(e){

        var picker_id=e.target.id;
        var selected_value = $('.selectpicker option:selected').val();
        var optgroup = ??

        switch ( optgroup){
            case "group_name":

            break

        }
});    

Thanks for help.

2

There are 2 answers

1
Pete On BEST ANSWER

You can try the following:

$('select.selectpicker').on('change', function(e){
    var picker_id=e.target.id;
    var selected_option = $(this).find(":selected"); // get selected option for the changed select only
    var selected_value = selected_option.val();
    var optgroup = selected_option.parent().attr('label');

    console.log(optgroup);
    switch ( optgroup){
        case "group_name":

            break

    }
}); 

Example

1
bvakiti On

Do you want to get the optgroups those are in '.selectpicker' class. If that is the case you can get using

$('.selectpicker optgroup').length // will give you optgroups in the   selectpicker.
$('.selectpicker optgroup')[0].label // you can access attributes