Tuesday, 25 September 2012

Add and remove textbox dynamically with jQuery.

Recently when working on my site i got a requirment wherein i user can add multiple input text on page in different textboxes, and these textboxes needs to be created dynamically as per user need. So i decided to do it in jQuery. it’s quite easy to add or remove a textbox dynamically. The idea is quite simple, just combine the use of ‘counter‘ variable, jQuery createElement(), html() and remove() method. See below example :


<html>
<head>
<title>Add dynamic text box</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>add dynamic text box</h1>
<script type="text/javascript">
 $(document).ready(function(){
     var counter = 2;
     $("#addButton").click(function () { //add dynamic text box
  if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
}   
  var newTextBoxDiv = $(document.createElement('div'))
    .attr("id", 'TextBoxDiv' + counter);
  newTextBoxDiv.after().html('<label>Textbox #'+counter+':</label>'+'<input type="text" name="textbox'+ counter+'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
     });

     $("#removeButton").click(function () { //remove dynamic text box
if(counter==1){
 alert("No more textbox to remove");
 return false;
   }   
counter--;
        $("#TextBoxDiv" + counter).remove();
     });

     $("#getButtonValue").click(function () {

var data = '';
for(i=1; i<counter; i++){
     data += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
     alert(data);
 //save dynamic data in database;
/* for(i=1; i<counter; i++) { 
        $.post(
            'process.php',// Data will be passed to this php file. 
           
                value: $('#textbox'+i).val() // get data values
            }
            );
  }*/
     });
  });
</script>
</head>


<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

</body>
</html>

No comments:

Post a Comment