4

I'm trying to set the default selection in a select menu in JQuery mobile. The docs have this:

   var myselect = $("select#foo");
   myselect[0].selectedIndex = 3;
   myselect.selectmenu("refresh");

Which I added right underneath where I create the menu, but then when I run the code I get this error:

throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'";

Not sure what to do at this point...

RK-
  • 12,099
  • 23
  • 89
  • 155
meds
  • 21,699
  • 37
  • 163
  • 314
  • The problem is you're manipulating objects that don't exist yet. Did the modified example I provided (binding the code to the pagecreate even of the containing page) solve your error? – ironchefpython Jun 17 '11 at 13:10

3 Answers3

7

You're trying to manipulate DOM objects with javascript that haven't loaded yet. Move the javascript past the form you're trying to manipulate, or more your code into a function that executes on document load.

For example:

$('#PAGE').live('pagecreate',function(event){
    var myselect = $("select#foo");
    myselect[0].selectedIndex = 3;
    myselect.selectmenu("refresh");
});

where PAGE is the id of the page you're loading that contains the menu you want to manipulate.


EDIT:

I updated the example to use the JQuery Mobile pagecreate event based on jinyuan's comment regarding JQuery Mobile events.

ironchefpython
  • 3,409
  • 1
  • 19
  • 32
  • 1
    document.ready doesn't work for jqm. use .live() to bind event such as 'pageshow,pagehide' check the demo for the list of events. http://jquerymobile.com/test/#/test/docs/api/events.html – root Jun 17 '11 at 04:07
  • position of JS related to markup tells you very little, almost nothing about when those are "live" – Jaroslav Záruba Sep 18 '12 at 11:34
3

As jQuery function:

$.fn.jqmSelectedIndex = function(index){
    var self = $(this)
    self
        .prop('selectedIndex', index)
    .selectmenu("refresh");

    return self;
}

$("select#foo").jqmSelectedIndex(3);

This isn't validated but works.

Renzo Castro
  • 186
  • 1
  • 6
1

it works. maybe you might want to provide more details.

http://jsbin.com/ekayu3/2

root
  • 1,573
  • 3
  • 23
  • 38