Dynamically Add Input Fields To Form Using jQuery

As jQuery is so powerful and it is easy to learn, it attracts huge volume of web developers. In this post I will show how to dynamically create input fields in a web page. Well you can use the logic to create other elements dynamically in a webpage.
You can check the LIVE DEMO.
You can use my tutorial on inserting record in database using jQuery and php and combine it with this tutorial to create a wonderful dynamic form accepting inputs from user and insert it in your database. The code is pretty easy to interpret and understand how it works. Here is our code:
1<html>
2<head>
3<title> Dynamically create input fields- jQuery </title>
4<script  src="https://<span class="IL_AD" id="IL_AD7">ajax</span>.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>        // Calling jQuery Library hosted on Google's CDN
5<script type="text/javascript">
6$(function() {
7var addDiv = $('#addinput');
8var i = $('#addinput p').size() + 1;
9 
10$('#addNew').live('click', function() {
11$('<p><input type="text" id="p_new" size="40" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="#" id="remNew">Remove</a> </p>').appendTo(addDiv);
12i++;
13 
14return false;
15});
16 
17$('#remNew').live('click', function() {
18if( i > 2 ) {
19$(this).parents('p').remove();
20i--;
21}
22return false;
23});
24});
25 
26</script>
27 
28</head>
29<body>
30<h2>Dynammically Add Another Input Box</h2>
31 
32<div id="addinput">
33<p>
34<<input type="text" id="p_new" size="20" name="p_new" value="" placeholder="Input Value" /><a href="#" id="addNew">Add</a>
35</p>
36</div>
37 
38</body>
39</html>
Note: You can dynamically add any other element using the same logic. So try your hands on some coding and get awesome results.

Comments

Popular posts from this blog

Real-Time Web Interface to MQTT using Socket.io and Node.js

Insert session variable into MySQL database

Insert CheckBox and Radio button Data in MySQL Database Using PHP