Search code examples
javascriptjqueryjquery-ui-selectmenu

selectmenuchange appending object list only on first event


I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.

SCRIPT

$("#parent").selectmenu();
$("#members").selectmenu();

var allMembers = $('#members option'); // keep object list of all of the options for the select menu

$("#parent").on("selectmenuchange", function() {
    var someMembers = [];
    var id = $('#parent option:selected').data('id');
    allMembers.each(function() {
        if ($(this).data('parent-id') == id) {
        someMembers.push($(this))
        }
    });
    $('#members').empty().append(someMembers);
});

At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.

I can't figure out if this is a problem with selectmenuchange or empty().append()

HTML

<select name="members" id="members">
    <option data-id="101" data-parent-id="1">Name1</option>
    <option data-id="102" data-parent-id="1">Name2</option>
    <option data-id="103" data-parent-id="1">Name3</option>
    <option data-id="104" data-parent-id="2">Name4</option>
    <option data-id="105" data-parent-id="2">Name5</option>
    <option data-id="106" data-parent-id="3">Name6</option>
    <option data-id="107" data-parent-id="3">Name7</option>
</select>

<select name="parent" id="parent">
    <option data-id="1">Parent1</option>
    <option data-id="2">Parent2</option>
    <option data-id="3">Parent3</option>
</select>

Solution

  • Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:

    $('#members').html(someMembers).selectmenu('destroy').selectmenu();
    

    DEMO