I want to add "product compare feature" in my website product list. I am wondering how can I make a Query String URL from product list page using jQuery. Looks lik
You need to somehow keep track of the items that have been selected. That could be an array variable that you updated both on add and remove, but it could also be indicated in the .box
elements you're creating. If you wrap the product ID in a span in the .box
elements as well, you'll have an easier time targeting the ID:
$('<div/>', { 'class': 'box' })
.append($('<span/>', { class: 'prod-id', text: id }))
.append($('<a/>', { href: '#', text: 'x' }))
.appendTo('#container');
You could then do:
var ids = $('.box .prod-id')
.map(function(i, x) { return ['P', ++i, '=', $(this).text()].join(''); })
.toArray();
$('#container > a').attr('href', 'Compare.html?' + ids.join('&'));
Demo
Update:
Your additional requests are easily fulfilled now that we've established a way of retreiving the added products' IDs. Since we'll be reusing it, I've extracted getSelectedIds
as a function of its own.
Now we just need to check its length
to test the max 4 requirement, and its indexOf(id)
to test whether the item was already added. If so, the code will just exit the .more
click listener. You could show the user an error message at that point.
Updated demo