I'm having trouble updating a jQuery Mobile select. On demand I want to change the contents and update the selected value.
Here's the fiddle (code below): http://jsfiddle.net/cjindustries/0cmg8vvt/2/
I'm getting this error in the console (along with the select not updating): Uncaught Error: cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'
I've seen similar things here on SO but none of the answers I've found fix my issue. We're using jQueryMobile 1.3.1 and jQuery 1.9.1.
Any help would be appreciated :)
Thanks, Chris.
Code...
<div data-role="page" id="p1">
<div data-role="content">
<h1>Page 1</h1>
<select class="pageSelect"></select>
<a href="#" id="update-select-1" data-role="button">Update Select Menu</a>
</div>
</div>
function generateOptions() {
var numbers = [],
html = "";
for (var i=0; i<100; i++) {
var v = Math.random();
numbers.push(v);
html = html + '<option value="' + v + '">' + v + '</option>';
};
return {
html: html,
value: numbers[5]
};
};
$(document).on('click', '#update-select-1', function() {
var options = generateOptions(),
select = $.mobile.activePage.find('.pageSelect');
select.html(options.html);
select.val(options.value);
// This updates the select but I lose styling
// select.selectmenu().selectmenu('refresh', true);
// This fails
select.selectmenu('refresh', true);
});
Don't use .pageSelect
as selector, because jQM will create an additional element with this style. When you do
´select = $.mobile.activePage.find('.pageSelect');
select.html(options.html);
select.val(options.value);´
you are inserting html code in two elements, the select and the rendered object, and because of that, you lose styling.
Try this:
$.mobile.activePage.find('select[class=pageSelect]').html(options.html).select('refresh');
http://jsfiddle.net/cjindustries/0cmg8vvt/
Also, if you are starting with jQM, consider moving to v1.4.