Dynamically Add Remove Elements using jQuery

Dynamically Add Remove Elements using jQuery
Advertise Here

Sample code snippet for Adding and Removing the Elements dynamically using jQuery

<div id="choiceTemplate"><input id="answercount" name="answercount" type="hidden" value="1" />
<div id="current1">Answer Choice 1 :
<input id="answer1" name="answer[]" size="20" type="text" /></div>
</div>
<div id="addremovelink" style="clear: both;"><a id="removechoice" href="javascript:;">Remove</a>
<a id="addchoice" href="javascript:;">Add Choice</a></div>

Javascript

$(document).ready(function() {
$("#addchoice").click(function(){
//getting the current element count
var current = $("#answercount").val();
current = Number(++current);
//Append the html content
$("#choiceTemplate").append("
<div id="current" + current + "">Answer Choice " + current + " :
<input id="answer" + current + "" name="answer[]" size="20" type="text" /></div>
");
//assign the current element count
$("#answercount").val(current);
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);
});
});

Submitted By : Raja

Demo 

You can leave a response, or trackback from your own site.

6 Responses to “Dynamically Add Remove Elements using jQuery”

  1. Harry says:

    Hi Raja,

    Thanks for the post, What plugins we require to run the above mentioned code?

    Thanks
    Harry

  2. admin says:

    Hi Harry,

    No plugin needed..this is simple jquery code.

    any issue with the above code? i am happy to help you.

    Thanks,
    Raja.

  3. anish says:

    one error on .append() function

  4. admin says:

    Please check the demo and see view source of demo http://ajaxmint.com/demo/add-remove-elements.html

    the below line
    $("#choiceTemplate").append("

    Answer Choice " + current + " :

    ");

    should be

    $("#choiceTemplate").append("

    Answer Choice " + current + " :

    ");

  5. vishal says:

    its really demanding.
    thanks for this code

  6. anand says:

    Hi,
    i would like to place the remove button near each input field, so that the user can remove a specific text field…
    can u plz help me ? :)

Leave a Reply

Subscribe to RSS Feed Follow Ajaxmint on Twitter!
Get Adobe Flash playerPlugin by wpburn.com wordpress themes