In a recent project I had the need to create checkboxes dynamically from a dataset.
My project was done in MVC 3 sprinkled with jQuery.
[gallery ids="118,123"]
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery Build Dynamic Checkboxes</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<style type="text/css">
.wrapper{ padding: .5em; border: 1px solid #d81c3f; border-radius: 5px; min-height: 500px; }
</style>
</head>
<body>
<div>
<div class='poo'>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
(function(){
var chkContainer = $('.poo');
var ccId = '1320';
if(ccId){
// Call to get your data
var shoeTypes;
if(ccId === '1320'){
shoeTypes = [
{ description: 'Runner' , available: true, enabled: true},
{ description: 'Jogger', available: true, enabled: true },
{ description: 'Sprinter', available: null, enabled: null },
{ description: 'Walker', available: true, enabled: true },
{ description: 'Couch', available: null, enabled: null }
];
} else {
shoeTypes = [ ];
}
}
$.each(shoeTypes, function(index, item){
// Build the Checkbox
var chk = '<input type="checkbox" name="' + item.description + ccId + '" ';
(item.enabled) ? chk += 'checked="true" ' : chk += '';
(!item.available) ? chk += ' disabled="true"' : chk += '';
chk += " />";
$(chk).appendTo(chkContainer);
// Build the Label for the Checkbox
$('<label for="' + item.description + ccId +'">' + item.description + '</label>').appendTo(chkContainer);
});
})();
</script>
No comments:
Post a Comment