JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container" class="hidden">
<p>There are 0 boxes</p>
<a href="\compare.html?a=123&b=124&c=125">Compare</a>
</div>
<div>
<div>
<h1>Product Name 1</h1>
<a href="#" class="more"> + Add to compare</a>
<span class="ProdId">123</span>
</div>
<div>
<h1>Product Name 2</h1>
<a href="#" class="more"> + Add to compare</a>
<span class="ProdId">124</span>
</div>
<div>
<h1>Product Name 3</h1>
<a href="#" class="more"> + Add to compare</a>
<span class="ProdId">125</span>
</div>
<div>
<h1>Product Name 4</h1>
<a href="#" class="more"> + Add to compare</a>
<span class="ProdId">126</span>
<div>
<h1>Product Name 5</h1>
<a href="#" class="more"> + Add to compare</a>
<span class="ProdId">127</span>
</div> </div>
</div>
CSS
body { font-family:Helvetica, Arial, sans-serif; font-size:12px; line-height:1.5; }
.more { color: green; }
.box {
display:inline-block;
width:50px;
height:25px;
background:#2d89ef;
margin:5px;
cursor:pointer;
text-align:center;
}
.box a {
display:inline-block;
width:20px;
height:20px;
color:#fff;
text-decoration:none;
}
.hidden{
display:none;
}
JavaScript
function getSelectedIds() {
return $('.box .prod-id').map(function() { return $(this).text(); }).toArray();
}
function updateLinkAndCounter() {
var ids = getSelectedIds().map(function(x,i) { return ['P', ++i, '=', x].join(''); });
$('#container > a').attr('href', 'Compare.html?' + ids.join('&'));
$("p").text(ids.length == 1 ? 'There is 1 box.' : 'There are ' + ids.length + ' boxes.');
}
$(".more").click(function() {
var id=$(this).next('.ProdId').text();
var selected = getSelectedIds();
if(selected.length == 4) return; // already 4 items added
if(selected.indexOf(id) != -1) return; // item already added
$('<div/>', { 'class': 'box' })
.append($('<span/>', { class: 'prod-id', text: id }))
.append($('<a/>', { href: '#', text: 'x' }))
.appendTo('#container');
updateLinkAndCounter();
$("#container").removeClass("hidden");
});
$(".box a").live("click", function() {
$(this).parent().remove();
updateLinkAndCounter();
});