Add and Remove items with jQuery

0

jQuery has been around for a while but only about a year ago I started to use it and understanding how easier life can be when using and implementing solutions with jQuery.
Creating web apps nowadays means creating something the user can control and many times that means letting them create, add and remove something from the interface you conceived.

Today I’m sharing a short and simple tutorial that will teach how to add and remove items from your HTML code using the functions appendTo(); and remove(); from jQuery.
For this particular example I’m not going to be careful creating valid markup although I recommend you to always follow the W3C directives.

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.

Labels:
Loading related posts...

0 comments:

Post a Comment

2010 WEBSITE20. All rights reserved.