So this is a problem I have seen all over the internet but I cannot for the life of me figure out why it won’t work.
For people who will have an idea of what I’m attempting – I have loaded in the static input stuff using .html(contentVariable) and it works fine but once I put the checkbox creation in a for loop everything goes to pot and only the first check box element seems to be working and have styles applied.
So I’m running a query on the server which is returning a json object in order to populate my checkboxes. In the JS I am using ajax to get this json object and loop through the contents to populate the checkboxes. The ‘result’ variable in the example below is returning 3 results and that side of things is working fine (if people realise that I’m not actually echoing out results from the returned object).
So my guess is I’m not using the .trigger() in the right place or correctly at all. Any help would be appreciated.
Many thanks.
HTML
<!-- register page -->
<div data-role="page" id="two">
<script type="text/javascript" src="js/friendsList.js"></script>
<div data-role="header">
<h1>New Project</h1>
<a href="#two" class="ui-btn-left" data-rel="back" data-icon="back" data-transition="flip">Back</a>
</div>
<div data-role="content">
<form id='registerUser' action="" method="POST">
<div data-role="fieldcontain" class="checkWrap">
</div>
<button type="button" aria-disabled="false">Submit</button>
</form>
</div>
</div><!-- /page two -->
JS
$(document).delegate('#two', 'pageshow', function() {
var userId = localStorage.getItem('userId');
var friendsListContent = "";
$.ajax({
url: 'http://www.mysite.co.uk/app/friends/listFriends.php',
type: 'post',
data: {'userId': userId},
dataType: 'json',
crossDomain : true,
timeout: 5000,
success: function(result){
friendsListContent = "<fieldset data-role='controlgroup'><legend>Choose as many snacks as you'd like:</legend>";
for(var i = 0; i < result.length; i++){
friendsListContent += "<input type='checkbox' name='checkbox-1a' id='checkbox-1a' class='custom' /><label for='checkbox-1a'>Cheetos</label>";
}
friendsListContent += "</fieldset>";
$('.checkWrap').html(friendsListContent);
$('.checkWrap').trigger('create');
$("input[type='checkbox']").checkboxradio("create");
},
error: function(){
alert('There was an error loading the data. Contact the admin.');
}
});
});
Okay so the answer is the fact that the numbers in the classes and names weren’t being iterated through with each of the checkbox items.
In the for loop I changed it to this…