Reputation: 3172
I want to create checkboxes dynamically. I am doing that, however I am failing with setting the name of the label. I tried setting the inner html to a value, though it didn't work. What is the correct way to do it ? source:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" >
<fieldset data-role="controlgroup" id="exampleGroup">
</fieldset>
</div><!-- /page -->
</body>
<script>
var someId = "Something";
for (var i = 0; i < 5; i++) {
var checkBox = $('<input>', {
type: "checkbox",
class: "custom",
id: someId + i.toString()
});
var checkBoxLabel = $('<label>', {
for : someId + i.toString(),
});
checkBoxLabel.innerHTML = "Hello world!"; // didn't work
checkBox.appendTo("#exampleGroup");
checkBoxLabel.appendTo("#exampleGroup");
}
</script>
</html>
Upvotes: 1
Views: 61
Reputation: 582
Try this
var someId = "Something";
for (var i = 0; i < 5; i++) {
var checkBox = $('<input>', {
type: "checkbox",
class: "custom",
id: someId + i.toString()
});
var checkBoxLabel = $('<label>', {
for: someId + i.toString(),
});
checkBoxLabel.text(someId + i.toString());
checkBox.appendTo("#exampleGroup");
checkBoxLabel.appendTo("#exampleGroup");
}
Following is the area you want to look at
checkBoxLabel.text(someId + i.toString());
I used jquery text to change the label text
Upvotes: 0
Reputation: 4043
Use text()
or html()
to set the contents of a DOM node. The difference between them is how they handle HTML tags.
checkBoxLabel.html('<foo>');
// <label><foo></label>
checkBoxLabel.text('<foo>');
// <label><foo></label>
You should prefer text()
when you do not need HTML.
Upvotes: 0
Reputation: 35963
Using text()
you can set the text inside label
try this:
checkBoxLabel.text("Hello world!");
Upvotes: 1