javascriptjqueryjquery-uijquery-ui-selectmenujquery-ui-menu

jQuery UI Menu get/set for active ui-menu-item


I need to do a multi dropdown menus using jQuery UI Menu. Before that we used jQuery UI Selectmenu for this purposes.

Selectmenu was based on select, where there can be used a val() method to get/set select value. Now menu is based upon ul/li and so I have no such option.

So I need to emulate somehow following behahior:

someMenu.menu();
//....                
someMenu.val(someValue);
someMenu.menu("refresh");

I've tried to extend the menu widget and add some methods like:

 $.widget("market.multiDropdownMenu",$.ui.menu, {
    //....
    getSelectedItem: function () {
        return this.active;             
    },

    setSelectedItem: function(elem){
        var elem = this.element.find(elem).first();
        if (elem) {
            this.active = elem;
            this.focus('focus', elem);
            this.element.find('.ui-menu-item.selected').removeClass('selected');
            this.getSelectedItem().addClass('selected');  
        }
    },
    //....
}

And then using it like:

// for getter
var elem = someMenu.multiDropdownMenu("getSelectedItem"); // getting null
// and for setter
var newElem = ...
someMenu.multiDropdownMenu("setSelectedItem", newElem);
someMenu.multiDropdownMenu("refresh");

But after setting some value and trying to get it back next time the active field is null.

I also tried to use elem.trigger('click'); instead focus event with no success.


Solution

  • It's not entirely clear to me what you want to do here, but possibly what you could do is set a class for whichever element in you menu is selected. Then, if you want to know which is selected you just use that class.

    Set selected:

    $( "#menu" ).menu({
        select: function(event, ui) {
            $('.selectedItem').removeClass('selectedItem');
            $(event.currentTarget).addClass('selectedItem');
    
        }
    });
    

    Get selected value:

    $('.selectedItem').text();
    

    Fiddle