简体   繁体   中英

Inconsistent behaviour when selecting multi-select element

I have a modal dialog which has a multi-select form element. On screen, I have two buttons - each with different options associated with them (one associated with 'Admins' and the other associated with 'Users')

When the user clicks on any button, jQuery identifies which option the button is associated with and then pre-selects the option on the multi-select list element in the modal dialog. All good thus far. The function works if I do it once - but if I do it repeatedly or select one button and then another button the option doesnt appear pre-selected. Am unable to identify where the bug is.

Any insight is appreciated - link to jsFiddle

The jQuery code is below - not sure why this is behaving in an inconsisten manner if I randomly select the buttons

$(document).on("click", ".btn", function () {

    $('.modal-body #name').val('John');

    $('.modal-body #email').val('john@acme.com');

    var groupNames = $(this).data('group-names');
    $('.modal-body #groups > option').each(function () {
        if (groupNames.search($(this).text()) == 0) {
            $(this).attr('selected', true);
        } else {
            $(this).attr('selected', false);
        }
    });

});

Try just setting the value of the <select> using val() . It's far simpler than looping over each option

$(document).on("click", ".btn", function () {
    var groupNames = $(this).data('group-names');
    $('.modal-body #groups').val(groupNames);
});

DEMO

@charlietfl 's response is the best approach. But the reason your code works inconsistently (in some browsers) is that you should set the selected property instead of attribute, like this:

$(this).prop('selected', 'selected');

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