Skip to content Skip to sidebar Skip to footer

How To Dynamically Create A Form Element

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, he

Solution 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
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="somediv">DIV</div>

Solution 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.

Solution 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 })));
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="target"></div>

Post a Comment for "How To Dynamically Create A Form Element"