Jan 1, 2011

Add controls (textbox, radio, checkbox..) dynamically in jQuery way

Generally, it is required to add elements like button, textbox, checkbox,radio ..etc dynamically in html form. This article explains how to add form elements dynamically in jQuery way. Let us take an example. Suppose we have to add controls on button click. See following HTML code:

<div style="display:inline">
<input type="button" id="txtPlain" value="Add Plain Text" style="" />
<input type="button" id="txt" value="Add TextBox" style="" />
<input type="button" id="chk" value="Add CheckBox" style="" />
<input type="button" id="rad" value="Add Radio" style="" />
<input type="button" id="btn" value="Add Button" style="" />
<div id="holder">

There are five buttons to add simple text, textbox, checkbox, radio and normal button.
See following jQuery code to add controls in holder division:

var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'}).addClass("text");
var $ctrl = $('<input/>').attr({ type: 'checkbox', name:'chk'}).addClass("chk");
var $ctrl = $('<input/>').attr({ type: 'radio', name:'rad'}).addClass("rad");
var $ctrl = $('<input/>').attr({ type: 'button', name:'btn',value:'Button'}).addClass("btn");
var lbl = prompt ("Enter Text","");

It is done in jQuery way. The fastest way is to create control using $(document.createElement(‘input’)) because
$(‘<input/>’) uses document.createElement.

Hope, It helps.


  1. I was suggested this website by way of my cousin. I am now not positive
    whether this put up iis written through him as nobody elose know such targeted approximatrely my difficulty.
    You are wonderful! Thanks!

  2. This might be an old post but good idea of creating controls in jquery. I am new to mvc am working on mvc4 i want to add controls in view and when click on save pass the data to controller to save it in DB. what i need is how to pass the holder div data to controller. Thanks in advance.

  3. I’ve been working with jQuery for a couple years but only recently began using it to generate dynamic markup. This is the best explanation of how to create dynamic forms that I’ve found. Excellent work, and thanks for taking the time to share your knowledge! 

  4. how to add attribute name from a variable?
    var “tname”=”id”
    i tried
    var $ctrl = $(”).attr({ type: ‘button’,”#tname”: ‘myID1′, name:’btn’,value:’Button’})
    but no luck..

  5. You can id easily similar to name, see following:
    var $ctrl = $(”).attr({ type: ‘button’, id : ‘myID1′, name:’btn’,value:’Button’}).addClass(“btn”);

  6. how to give each control an id fr example
    input type= textarea name =”textarea 1″
    input type= textaea name =”textarea 2″

  7. something like this:

    .text(‘Select a city / town in Sweden’)

Leave a Reply

Your email address will not be published. Required fields are marked *