brain storm brain storm - 9 months ago 21
Javascript Question

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, here is the code without labels
This is what expect

<input type="radio" name="Alex" value="Alex"/>Alex

value: "Alex",

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

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


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=""></script>
<div id="somediv">DIV</div>