SO Help: Auto style checkbox with jQuery ui theme
by SpYk3
HTML
<link rel="stylesheet" href="http://jqueryui.com/css/base.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.23/themes/base/jquery-ui.css">
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css">
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<center>
<button>Create New CheckBox</button>
</center>
<hr />
<div id="CheckBoxes">
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
</div>
CSS
.inp-checkbox {
}
.inp-checkbox+label {
margin: .5em;
width:16px;
height:16px;
vertical-align:middle;
}
JavaScript
function createCheckBox(ele, i) {
var newID = "cbx-"+i;
ele.each(function(cnt) {
if ($(this).attr("id") == undefined) $(this).attr({ "id": newID });
$(this).prop({ "type": "checkbox" })
.after($("<label />").attr({ for: $(this).attr("id") }))
.button({ text: false })
.click(function(e) {
var toConsole = $(this).button("option", {
icons: {
primary: $(this)[0].checked ? "ui-icon-check" : ""
}
});
//console.log(toConsole, toConsole[0].checked);
});
});
return ele;
}
$(function() {
$(".inp-checkbox").each(function(i) {
var newCheckBox = createCheckBox($(this), i);
console.log(newCheckBox);
});
$("button").button().on("click", function(e) {
var checkBoxCount = $("#CheckBoxes .inp-checkbox").length;
var newCheckBox = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes"));
createCheckBox(newCheckBox , checkBoxCount);
console.log(newCheckBox);
});
// just for fun, this will send a jQuery object with "2" inputs to our function and still produce the same result but with 2 checkboxes instead of one
// of course this would really require some crafty rework on our counter
// but as i mentioned before, that method it but "1" of MANY ways to make this addition
setInterval(function(){
var checkBoxCount = $("#CheckBoxes .inp-checkbox").length;
var newCheckBox = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes")).attr({ "id": "cbx-"+($("#CheckBoxes .inp-checkbox").length) }),
newCheckBox2 = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes")).attr({ "id": "cbx-"+($("#CheckBoxes .inp-checkbox").length) }),
chkBxs = newCheckBox.next().andSelf();
createCheckBox(chkBxs, checkBoxCount);
//console.log(chkBxs);
}, 1000);
...