Thursday, June 14, 2012

JQM: Refresh jQuery Mobile Select Menu

Suppose you are adding select menu to the page dynamically using JavaScript, jQuery mobile will not style the select menu. So have to refresh the select menu.
$('.mySelectMenu').selectmenu('refresh', true);
Sometime we might get an error like: "Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'". To resolve it by first initialize the select menu and then refreshing it.
$('.mySelectMenu').selectmenu('refresh', true);
20 Nov 2012: Update with JQM 1.2.0 code explanation given below.
Make sure that the selector returns items which are all select nodes. Otherwise JQM will throw the above mentioned error. See the below JQM code.
// jQM v1.2.0: line 516
// ...
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
// ...
// ...
The code at line 6 checks for mobileSelectmenu property in the current element and assigns to the instance variable. If the current item is not select then the instance is null and we get the error.