Sunday, March 6, 2011

Add Drop down or list dynamically into an HTML form

In the previous articles we have discussed about how to different dynamic actions related to a select input field in an HTML form, in whatever form or name it is, i.e. the same is called a drop down list or list box or combo box. Now in this article I want tell you how to insert a select field dynamically to an HTML form. This too using the same java script or jquery APIs. Sure you can do the previous experiments of inserting options or deleting it or counting or set a new value as selected all using the same code discussed in previous articles. So let us do it, add a drop down to a form.

The javascript code to achieve this task is,

var my_form = document.getElementById('id_form');
var my_select = document.createElement('select');
my_select.setAttribute('id','id_select');
my_form.appendChild(my_select);

Note:-
1. Replace the 'id_form' with the id of the form to which you want to insert the select element
2.Replace the 'id_select' with the id you want to use for the newly added select box.

The same using jquery,

$("#id_form").append('<select id="id_select"></select>');

For eg:-

If the HTML code is as below then the javascript and jquery code following it can be used to do the same,

<form id="test_form">
<input type="text" name="name" value="test" >
</form>

javascript code,

var my_form = document.getElementById('test_form');
var my_select = document.createElement('select');
my_select.setAttribute('id','test_select');
my_form.appendChild(my_select);

jquery code:

$("#test_form").append('<select id="test_select"></select>');

If you want mix the jquery APIs and the javascript (the core java script I mean, jquery too is javascript itself, but a framework made of javascript), the same can be accomplished using the snippet,

var my_select = document.createElement('select');
my_select.setAttribute('id','test_select');
$("#test_form").append(my_select);

Hopes you enjoyed this code, if you need any more explanation or clarification feel free to put your comments.

No comments:

Post a Comment