Saturday, December 4, 2010

JQuery Mobile How to add items and get selected items from menu

The following example is given in JQuery Mobile documentation.

<div data-role="fieldcontain">
<label for="select-choice-1" class="select">Choose shipping method:</label>
<select name="select-choice-1" id="select-choice-1">
<option value="standard">Standard: 7 day</option>
<option value="rush">Rush: 3 days</option>
<option value="express">Express: next day</option>
<option value="overnight">Overnight</option>
</select>
</div>


I wanted to do this dynamically by code. and my solution is given below



the array



var shippingarray = [
{ name: "Standard: 7 day", id: "Standard" },
{ name: "Rush: 3 days", id: "Rush" },
{ name: "Express: next day", id: "Express" },
{ name: "Overnight", id: "Overnight" },
{ name: "slow boat", id: "slow" }
]



Loading the menu



function Load_select_shipping() {

var arraytoload = shippingarray;
var optionlist = '';
var i = 0;
// <option value="volvo">Volvo</option>

$.each(arraytoload, function (index,item) {
if (i == 0) {
optionlist += '<option selected="' + item.id + '">' + item.name + '</option>';
}
else {
optionlist += '<option value="' + item.id + '">' + item.name + '</option>';
}
i++;
})
optionlist += '';
$("#select-choice-1").html(optionlist).selectmenu('refresh', true);

// $("#select-choice-1").html(shippingarray2).selectmenu('refresh', true);
}


to get the selected item



function Get_Data() {

$('#content_data_list').empty();
var index = $("#select-choice-1")[0].selectedIndex;

var selected_item = shippingarray[index].id;

shippingselected = "val: " + $("#select-choice-1").val() + " index: " + selected_item;
var listitem = '<li > ' + shippingselected + '</li>';
$('#content_data_list').append(listitem);
$('#content_data_list').listview('refresh');

}



Note the refresh. This has to be done for updating any lists to which add items!



Had interesting posts in JQuery Mobile given below:



Add items and refresh



How to get selected item



Add link buttons and refresh



JQuery Mobile Goto

No comments:

Post a Comment