Hector Barbossa
Hector Barbossa

Reputation: 5528

Dynamically add textbox using jquery

What's wrong with this code ? Only first add and remove link is working...

<html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
 div{
  padding:8px;
 }
</style>

</head>

<body>


<script type="text/javascript">

$(document).ready(function(){

    var counter = 2;

    $(".addButton").click(function () {

 if(counter>5){
            alert("Only 5 textboxes allow");
            return false;
 }   

 var newTextBoxDiv = $(document.createElement('div'))
      .attr("id", 'TextBoxDiv' + counter);

 newTextBoxDiv.html('<TABLE><TR><TD>' +
'<input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD><TD><input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD>&nbsp;<TD><a href="#" value="addButton" class="addButton">Add</a>&nbsp;<a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR></TABLE>');

 newTextBoxDiv.appendTo("#TextBoxesGroup");


 counter++;
     });

     $(".removeButton").click(function () {
 if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

 counter--;

        $("#TextBoxDiv" + counter).remove();

     });

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

 var msg = '';
 for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
 }
       alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
 <div id="TextBoxDiv1">
  <TR><TD><input type='textbox' id='textbox1' ></TD>&nbsp;<TD><input type="text" name="textbox' + counter + 
'" id="textbox' + counter + '" value="" ></TD>&nbsp;<TD><a href="#" value="addButton" class="addButton">Add</a>&nbsp;<a href="#" value="removeButton" class="removeButton">Remove</a></TD></TR>
 </div>
</div>

</body>
</html>

Upvotes: 4

Views: 21519

Answers (3)

Selvakumar Kaliyappan
Selvakumar Kaliyappan

Reputation: 106

you just add this file in your folder its works fine...!

jquery-1.3.2.min.js

Upvotes: 0

jlunavtgrad
jlunavtgrad

Reputation: 1015

Use of live() has been depreciated, and removed since Andy E's post. The same functionality is now supported using the following syntax:

$(document).on("click", ".removeButton", function () {

Upvotes: 1

Andy E
Andy E

Reputation: 344575

When you bind the click() handler, there's only one Add link on the page to bind to. Use live() to capture click events for elements that aren't on the page yet:

$(".addButton").live("click", function () {

Working demo: http://jsfiddle.net/u9hvp/

Upvotes: 10

Related Questions