问题
I have the following code I am trying to dynamically create radio button with and without labels in them. I am unable to put the text in radio button when I create radio button, here is the code without labels This is what expect
<input type="radio" name="Alex" value="Alex"/>Alex
$('<input>').attr({
type:'radio',
name:'name',
value: "Alex",
text:"Alex"
}).insertAfter("#divid"));
Now for having labels,
<label><input type="radio" name="Alex" value="Alex"/>Alex<label>
//create a label tag
var label = $('<label>', { text:"Alex"});
//append input tag to label
$(label).append($('<input>').attr({
type:'radio',
name:"Alex",
value:"Alex"
}).insertAfter("#divid"));
Both of the above does not produce any error on console but it does not produce the right HTML tag I am interested in. Also is there a way to directly add label to radio as I create them dynamically. I mean I dont want to create a label tag separetely and append to it the radio button. Many Thanks for your help
回答1:
Dynamically create label and radio
jsBin example
var $input = $('<input />', {
type : "radio",
name : "name",
value : "alex"
});
$("<label />", {
insertAfter: "#somediv", // (or use appendTo: to insert into it)
append: [$input, "Alex"] // include our $input and also some text description
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="somediv">DIV</div>
回答2:
You should replace var label = $('<label>').attr({ text:"Alex"}); with var label = $('<label>').text("Alex");
Also - you have few syntax errors in your code, I don't see what's so hard to copy+paste properly.
回答3:
I like Roko's answer, except that it's vulnerable to HTML injection if you're building the radio button labels from user content.
Here, I use the .text() method to make sure that the text is properly escaped.
var $target = $('#target'),
records = [{ id: 1, name: "Alex" },
{ id: 2, name: "Test that HTML <em>is not</em> injected" }];
$target.append('<h3>With Labels</h3>');
for (var i=0; i < records.length; i++) {
$target.append($('<label>').text(records[i].name)
.prepend($('<input type="radio" name="mychoice">',
{ value: records[i].id })));
}
$target.append('<h3>Without Labels</h3>');
for (var i=0; i < records.length; i++) {
$target.append($('<span>').text(records[i].name)
.prepend($('<input type="radio" name="mychoice">',
{ value: records[i].id })));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
来源:https://stackoverflow.com/questions/16973457/how-to-dynamically-create-a-form-element