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('<tr align="left" valign="middle" id="sampleTr" >'+
                    '<td width="12%" valign="bottom" class="content">'+

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

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

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

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


                    '<input style=" 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"