Karthiga Karthiga - 2 months ago 6
HTML Question

How to add one buttton2 while click another button1 and button 3 while click button2

In the below jquery file when i click add button it create one text box with one button after i click addbutton it create another textbox with button.......But what i want is when i cllick 1st button it add 2nd button then i click 2 nd button it add 3rd button .....But i doknow how to do ..

$(document).ready(function() {
var counter = 2;

$("#addButton").click(function() {
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="" >' +
' <input type="button" value="Add Button" id="addButton">');

newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});

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

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

Answer
  • Duplicate IDs are invalid HTML and will nearly always cause issues with scripting. Avoid if at all possible.
  • The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on(). More details: http://api.jquery.com/on/

Your Sample:

$(document).ready(function(){

    var counter = 2;

		$(document.body).on('click', ".addButton", function(){

    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="" >' + 
          ' <input type="button" value="Add Button" class="addButton" id="button' + counter + '">');

    newTextBoxDiv.appendTo("#TextBoxesGroup");
    $(this).attr( "disabled", "disabled" );

    counter++;
     });

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

    counter--;

        $("#TextBoxDiv" + counter).remove();
        $("#button" + (counter - 1)).attr( "disabled", false );
        if(counter==2){
             $(".addButton").attr( "disabled", false ); 
         }

     });

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
  <input class="addButton" type="button" value="Add Button" />
  <input class="removeButton" type="button" value="Remove Button" />
</div>
<div id="TextBoxesGroup"></div>

Comments