Skip to content Skip to sidebar Skip to footer

Dynamically Insert/remove Fields Using Jquery

In a jsp, I have a plus button and when user clicks it it dynamically generates fields. Now I want to add a remove link to each field newly added. I have inserted a button and wro

Solution 1:

You need to create a function instead of click event or bind a live event. Because your DOM was manipulated everytime you click on Add button.

Try updated code

<script>
    $(document).ready(function() {
       var iCnt = 1;
       // CREATE A "DIV" ELEMENT AND DESIGN IT USING JQUERY ".css()" CLASS.
       $('#plusbtn').click(function() {
          if (iCnt <= 14) {
            iCnt = iCnt + 1;
            // ADD TEXTBOX.
            $('#headingrow').append('<tralign="left"valign="middle"id="sampleTr" >'+
                    '<tdwidth="12%"valign="bottom"class="content">'+

                    '<selectstyle=" width:165px;"name=attrtype'+iCnt+' ' + 'class="content"id=attrtype'+iCnt+' ' + 'onchange="specialAttr(this);">'+

                    '<optionselected="selected"value="">-Data Type-</option>'+
                    '<optionvalue="text">Text</option>'+
                    '<optionvalue="number">Number</option>'+
                    '<optionvalue="currency">Currency</option>'+
                    '<optionvalue="percentage">Percentage</option>'+                                                                                               
                    '<optionvalue="date">Date</option>'+
                    '</select>'+

                    '<inputstyle=" width:165px;"name=attr'+iCnt+' ' + 'id=attr' + iCnt + ' ' + 'type="text"class="content"value=""placeholder="Attribute Name">'+

                    '<inputstyle=" width:95px;"name=attrDec'+iCnt+' '+ 'id=attrDec' + iCnt + ' ' + 'type="hidden"class="content"value=""placeholder="Decimal Points">'+


                    '<inputstyle=" width:90px; background-color: white; color: Red; border: 0px solid;"name="attrRem"id="attrRem"type="button"class="content"value="Remove"click="remove(this);" >'+   
                '</td>'+
            '</tr>');
        }
        // AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
        // (20 IS THE LIMIT WE HAVE SET)
        else {      
            $('#plusbtn').hide();
        }
    });
});
function remove(currObj){
      var $this=$(currObj); 
      $this.parent().remove();
}
</script>

Happy coding :)

Solution 2:

parent() method of jquery points to immediate parent. Which is in your case is "td" not "tr"

So, to solve this try to use .closest method instread of .parent()

 $('#attrRem').click(function(e){
            //window.alert(this.value);
            e.preventDefault();
            $(this).closest("tr").remove();
            iCnt = iCnt-1;
        });

Post a Comment for "Dynamically Insert/remove Fields Using Jquery"