Add and Remove items with jQuery

Creating the markup

In this example I’m going to create text field and 2 buttons that will allow me to add and remove text fields. Similar to online apps that allow you to create web form.

<a href="#" id="add">Add</a>
<a href="#" id="remove">Remove</a>

<p><input type="text" value="1" /></p>

The <p> around the input is just to add a new line when I add now input’s.

Applying jQuery to the markup

First you need to get jQuery. You can download it from the official jQuery website or use the link from Google Code: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

Now you need to call jQuery in the <head> section of you HTML Template using the script tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">&lt/script>

Now you need to add the jQuery under the script you just called:

<script type="text/javascript">

$(function() { // when document has loaded

	var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work

	$('a#add').click(function() { // when you click the add link
		$('<p><input type="text" value="' + i + '" /></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
		i++; //after the click i will be i = 3 if you click again i will be i = 4
	});

	$('a#remove').click(function() { // similar to the previous, when you click remove link
	if(i > 1) { // if you have at least 1 input on the form
		$('input:last').remove(); //remove the last input
		i--; //deduct 1 from i so if i = 3, after i--, i will be i = 2
	}
	});

	$('a.reset').click(function() {
	while(i > 2) { // while you have more than 1 input on the page
		$('input:last').remove(); // remove inputs
		i--;
	}
	});

});
</script>

Here you have it a simple . You need to keep in mind that every time you refresh the page the items will be gone. You’ll need more codding in order to keep the variables on a database. This is just to cover the basic add / remove functions from jQuery.

Add / Remove input with jQuery Demo

* Update – December, 31st 2010 *
jQuery Add/Remove with Dynamic PHP content
A thread was started at Question Lounge regarding this issue.

In this particular case the thread is based on assigning dynamic content to a select element. The select element has the ID of service-N, where N is a number (1 2 3 4, etc).

Here is a sample of the jQuery code:

$('select[id^="service-"]').change(function(){
   var id = $(this).attr('id');
   id = id.replace('service-', '');

   var someValue = $(this).val();

   $.get('/fetch/content/from/this/url?param='+someValue, function(data){
       $('#store-' + id).html(data);    // that would be if your script returns HTML.
                                        //  You can easily alter the functionality to
                                        // rebuild the dropdown menu from JSON object
                                        // or something like that
   });
});

For more information please visit this thread.

Usefull links
Theme Forest – Jquery for Absolute Beginners – Day 5
jQuery Homepage

13 comments

  1. Mario simples e eficientes as funções…

    Parabens

  2. wassim says:

    nice tutorial, this iss what i am lookin for, it’s the best

  3. Enrique says:

    Thank you! It was very helpful.

    Greetings from Mexico!

  4. Lucas says:

    Nice and easy, but it’s not working correctly in IE (tested in IE 7).

  5. how can I add the submit button and write the value at the field?

  6. Onion says:

    Hi, nice simple tutorial, thanks for that.
    I’m looking for one a slight bit more complicated where you can remove specific items, your “remove” button will always remove the last in the list. Can you recommend a good tutorial?

  7. JD says:

    Really like your little script here. I’ve been working on using for myself, but was wondering if you knew of a way to focus() on a particular input after adding a row. I already have unique ID’s/names worked out and what I’m trying to do is check the field with javascript and then say for example it is blank, refocus on the field.

    Here’s the modification I’m using:

    $(‘Username ‘ + i + ‘: ‘).animate({ opacity: “show” }, “slow”).appendTo(‘#inputs’);

    $(‘#user4′).focus(); works but only within
    $(‘a.add’).click(function() { …
    and obviously I have to validate the field first.

    Very confused because after validation I take the name of the field that is passed through the checkl() via onblue and tried this:
    document.getElementById(name).focus(); // doesn’t work
    document.getElementById(name).style.backgroundColor=”#72A4D2″; // works just fine!

    Any ideas on how to focus() would be appreciated. Thanks again for the script. :)

    • JD says:

      Apologies for some reason my comment appears incorrectly,

      $(‘Username ‘ + i + ‘: ‘).animate({ opacity: “show” }, “slow”).appendTo(‘#inputs’);

      should be:

      $(‘Username ‘ + i + ‘: ‘).animate({ opacity: “show” }, “slow”).appendTo(‘#inputs’);

      • JD says:

        Ha, must be wordpress killing the input. Here it is one last time:

        $(‘{}Username ‘ + i + ‘: {}{}’).animate({ opacity: “show” }, “slow”).appendTo(‘#inputs’);

        • JD says:

          You’ll probably just want to delete all of those repeats.

          But anyways, the modification I’m using is:

          $(‘<p>Username ‘ + i + ‘: <input type=”text” id=”user’ + i + ‘” name=”user’ + i + ‘” onblur=”javascript:checkl(this.name, this.value, 1, 10);”></p>’).animate({ opacity: “show” }, “slow”).appendTo(‘#inputs’);

          Lo siento, apologies Mário.

  8. Biju Subhash says:

    thank you for sharing.. .

Leave a Reply

Your email address will not be published. Required fields are marked *

*