Reputation: 17269
I have a JQM page with select
element:
<select class="state" name="user.state" data-role="select"><option value="">state</option></select>
Im trying to add option into it dynamically:
$.each(data['states'], function(index, state) {
$('<option value="'+state+'">'+state+'</option>').appendTo($('#update-profile-page .state'));
});
But it didn't worked as expected.
Screenshot:
The problem is that the values of the default or selected option contains all the states.
Upvotes: 2
Views: 12145
Reputation: 41
I hope this function contribute.
setSelect("typeBusiness",row["region"]);
function setSelect(idControl,newValue){
var select = $("#"+idControl);
var optsLength = $("#"+idControl+" > option").length;
var optTempl = "<option value='"+newValue+"'>"+newValue+"</option>";
select.append(optTempl);
var newOption= $($("option", select).get(optsLength));
newOption.attr("selected", "selected");
select.selectmenu();
select.selectmenu("refresh", true);
}
Upvotes: 0
Reputation: 6944
My Html code:
<div data-role="page">
<div data-role="header">
<h1>My Title</h1>
</div><!-- /header -->
<div data-role="content">
<p>Hello world</p>
<select class="state" name="user.state" data-role="select">
<option value="asfsafd">option1</option>
<option value="asfsafd">option2</option>
<option value="asfsafd">option3</option>
</select>
</div><!-- /content -->
<a data-role="button" id="test">click</a>
</div><!-- /page -->
JS code
<script>
$("#test").bind('click', function(){
var select = $('select.state');
$.each(["option4", "option5", "option6" , "option7"], function(index, state) {
var optTempl = '<option value="' +state+ '">'+state+'</option>';
select.append(optTempl)
});
var option4 = $($("option", select).get(4));
option4.attr('selected', 'selected');
select.selectmenu();
select.selectmenu('refresh', true);
})
</script>
I have modified your code a bit for explanation. I have added a button, and attached a click on that. while you click i dynamically append some random values , change the selected option to one of the options that was added dynamically. Then reinitialized the the select menu then refreshed the menu.
The last two line of the script is the answer.
Upvotes: 8