Reputation: 170
I am having a multiple select country checkbox list as shown below:
I have got an array with multiple values. Now whichever values from the array exists in the selectbox, I need to check the same dynamically. For which I am using :
$.each( myarray, function( key, value ) {
$('#Country option[value="'+value+'"]').attr('checked',true);
});
$('#Country').checkboxradio('refresh');
But I am not able to get the checkboxes selected.
Upvotes: 1
Views: 1505
Reputation: 760
I know my response is late but it may help you.
your array may like this {"foo1":"india","foo2":"Afghanistan","foo3":"Albania"};
$(document).ready(function(){
var myid,myvalue;
var object={"foo1":"india","foo2":"Afghanistan","foo3":"Albania"};
jQuery("input[name='country']").each(function() {
myid=this.id;
myvalue=this.value;
$.each(object,function(key,value)
{
if(value==myvalue)
{
$("#"+myid).attr("checked",true);
}
});
});
});
In html
<body>
<form>
<input type="checkbox" id="foo1" name="country" value="india">india
<input type="checkbox" id="foo2" name="country" value="Afghanistan">Afghanistan
<input type="checkbox" id="foo3" name="country" value="Albania">Albania
<input type="checkbox" id="foo4" name="country" value="Algeria">Algeria
</form>
</body>
</html>
Upvotes: 0
Reputation: 1135
The way jQuery mobile works is that it essentially uses your select/option elements to create it's own list and that list is the one we're seeing in your screen shot. The list does not use actual checkboxes, it uses classes .ui-checkbox-on and .ui-checkbox-off to simulate the selecting of an item.
So the snippet of code I made before gets the text (country names) of the options you want, based on the values provided in the first array and then uses it to add the necessary classes to the links that contain the text of the countries.
var myarray = ["4","248"];
$(myarray).each(function(key, value){ //for each element in array
var textarray = [$('option[value="4"]').text(), $('option[value="248"]').text()]; //get the text of each option based on it's value (you have to make this dynamic, I hard coded this) and put it in an array
$('#Country-listbox ul li').find('a:contains("' + textarray[key] +'")').addClass('ui-checkbox-on').removeClass('ui-checkbox-off'); //get the link that contains the text we want (which is in the array we made before) and add the class that checks the box and remove the class that takes the check off
});
Country-listbox is the name of the div that contains the list that jQuery creates based on your option/selects. It names the div the way it does based on the id of your select element.
Upvotes: 1