1

Suppose this is the prepare table below. and each of 3 row there was a textbox and beside them there where 2 buttons the + or add and - for delete. when i click + in a row, a new textbox will be generated and when i click - the textbox will delete. like the sample below: My question or sample that i cant do by my self ;-(


Could anyone suggest the snippet for this step or procedure?

Thank you

2 Answers 2

1

you could write something on these lines:

<script type="text/javascript">

$(document).ready(function(){

var counter = 2;

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

if(counter>10){
        alert("Only 10 textboxes are allowed");
        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 () {
if(counter==1){
      alert("No more textbox to remove");
      return false;
   }   

counter--;

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

 });
});
</script>

If you do not want to create the div on the fly, you can find the id of your last table row, add 1 to it, create the table row, and then append the textbox creation html to it.

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming the html structure is as follows

<table border = "1">
<thead>
    <tr><td> Text Boxes </td></tr>
</thead>
<tbody>
    <tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
    <tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
    <tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
</tbody>

​ the following jquery snippet should work

$(".add-text-box").click(function(){
    $(this).parent().prepend(" <input class='text-box' /> <br>");
});

$(".remove-text-box").click(function(){
    textboxes = $(this).parent().find('.text-box'); 
    $(textboxes).last().remove();
    if (textboxes.length === 0) {
        $(this).siblings().remove();
        $(this).remove();
    }        
});

​ You can see it in action here

1 Comment

kidmenot nice work but the problem is when i click - sign and only 1 textbox is remain it should be gone together with the buttons or the row instead thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.