Search code examples
jquery-mobilerefreshselect-menu

jQuery Mobile - changePage and select menu not working


This is my first time with jQuery Mobile and I'm actually using it from a WP theme I got. I understand that this might be theme related but I just want to make sure.

So, it is a Wordpress jQuery Mobile theme, you plug it and it works a treat. The thing is, I've converted the Wordpress menu from an UL to a SELECT.

I have then added some jQuery to fire the select on change by getting the value of the selected option. That works, I get the loading thinggy and then the page changes with my desired effect.

But I can't get the Select menu to show the current selected item. It always reverts to the first one.

I have used:

$('#main_menu').selectmenu("refresh");
$('#main_menu').selectmenu("refresh", true);

But nothing...

You can have a look at the site here: http://avatarblog.fl1hosting.com/ and look at the source.

You will see that my mobile event are all before the jQuery Mobile include, which doesn't make much sense to me, but if I put them afterwards, nothing works.

Any help would be highly appreciated!

Thanks


Solution

  • You need to set which option to show in the select menu. Try this,

    $("#main_menu")[0].selectedIndex = 2; // this will select the 3rd in the menu list
    $("#main_menu").selectmenu("refresh");
    

    You can add the following script your header.php:

    $(document)
    .unbind("pageshow.initMenuBtn")
    .bind("pageshow.initMenuBtn", 
        function() {
            $.mobile.activePage = $("div.ui-page-active");
            $("#main_menu", $.mobile.activePage)
              .unbind("change")
              .bind("change", function() {
                    var page = $(this).val();
                    $.mobile.changePage(page);
                });
    
            var selectedIndex = 0;
            $("#main_menu>option", $.mobile.activePage).each(function(index) {
                if ($(this).hasClass("current-menu-item")) {
                    selectedIndex = index;
                }
            });
            $("#main_menu", $.mobile.activePage)[0].selectedIndex = selectedIndex;
            $("#main_menu", $.mobile.activePage).selectmenu("refresh");
        });