brain storm brain storm - 7 months ago 10
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




$('<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

Answer

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>

Comments