Add remove element jquery OR add remove html jquery


  
Add /Remove dynamically HTML element with jQuery
  
First of all you must have to include jQuery library

jQuery Section

<script>
$(document).ready(function()
{
  $("#addchoice").click(function()
  {
    //getting the current element count
    var current = $("#answercount").val();
    current = Number(++current);
  
    //Append the html content
      
    if(current<=Number(3))
    {
      $("#choiceTemplate").append("<div class='inputsection' 
         id='current" + current + "'>Title " + current + ":
         <input id='title" + current + "' name='title[]' 
         size='20' type='text' /></div>");
            
      //assign the current element count
      $("#answercount").val(current);
    }


    if(current>=3){
      $("#addchoice").hide();
    }
  
    if(current==1){
       $("#removechoice").show();
    }
   
    return false;
  });

  
  //remove the elements
  $("#removechoice").click(function()
  {
    //getting the current/last element count
    var current = $("#answercount").val();

    //removing the element
    $('#current'+current).remove();
    
    //assign the current element count
    current = Number(--current);
    $("#answercount").val(current);

    if(current==0)
    {
      $("#removechoice").hide();
    }

    if(current<3){
      $("#addchoice").show();
    }

  });
});

</script>

HTML section

<div id="choiceTemplate">
   <input id="answercount" name="answercount" value="0"
       type="hidden">
</div>

<div id="addremovelink" style="clear: both;">
   <a id="removechoice" href="javascript:;" style="display:none;">
       Remove
   </a>
   <a id="addchoice" href="javascript:;">Add</a>
</div>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s