Grabbing Data From A Div With jQuery
jQuery is a powerful package that can grab and manipulate data within HTML very easily.
Let's assume we have the following code in place from say a shopping cart:
The bounding div "products" will hold all of our shopping cart items. Each item's ID will be it's product number and will be part of the class "shop_cart_item".
Now say we want to grab that data and summerize it for the user before final purchase in a new window, including final product info, pricing etc.
Set up our basket div:
var basket = $("#products").html();
Now, let's count how many products (or divs) we have in our basket:
var our_div_size = $("div").children('.shop_cart_item').length;
If you now alert(our_div_size); you will find, in our case the number 2. Meaning we have 2 products in the basket, which is good... let's continue!.
Set up an array to hold all our in-cart items where "our_div_size" is obviously the number of items in the cart and the number of items that will be in the array:
var our_items = new Array(our_div_size);
Run a for loop and go through each item, grab the "id" attribute in each which in our case is the product number and add it to our array:
for (var x = 0; x < our_div_size; x++) {
our_items[x] = our_divs.attr("id");
}
Tada! So now we have an array of all of our items. If you alert(items[0]); you will show the part number of the first item in our cart.
This can be very useful instead of grabbing all the HTML within the "products" div and posting it to a PHP page to parse. It can get very ugly fast. Instead now we can print out our array to a new window as the GET data, grab that data and do what we wish with it!.