Justin
Justin

Reputation: 329

How to dynamically clone text from element?

I am using a system that generates a shopping cart summary in a table with little room to customise. What I would like to do is when the shopping cart is 'empty' display '0'

When it has a quantity in it, display that number.

This is the generated HTML which I have hidden:

<span vertical="False" quote="False" id="catCartSummary">
   <table cellspacing="0" class="cartSummaryTable">
     <tbody>
       <tr>
         <td class="cartSummaryItem">3 item(s), Total: $115.00 <a href="/OrderRetrievev2.aspx?CatalogueID=0" class="cartSummaryLink">View Cart</a></td>
       </tr>
     </tbody>
   </table>
</span>

As you can see it currently has "3 item(s)".

This is what is looks like empty:

<span vertical="False" quote="False" id="catCartSummary">
   <table cellspacing="0" class="cartSummaryTable">
     <tbody>
       <tr>
         <td class="cartSummaryItem">Shopping cart is empty.</td>
       </tr>
     </tbody>
   </table>
</span>

Now I have some simple HTML setup here:

<div class="cartsummary">
  <div class="cartitems">Shopping Cart <a href="#"><span class="cartTotal"></span> Item(s)</a></div>
</div>

Using jQuery I'd like to then take the quantity and add it to .cartTotal and if there's nothing in the cart just show 0.

This sort of works but if I add a new item to the cart it only updates the value when the page is refreshed, whereas the auto generated updates dynamically.

if (jQuery('#catCartSummary .cartSummaryItem').html() != 'Shopping cart is empty.') {
   var summary = jQuery('#catCartSummary .cartSummaryItem').text().split(" ");
   var total = summary[0];
   jQuery('span.cartTotal').html(total);
}else{
   jQuery('span.cartTotal').html("0");
}

Few extra's worth noting:

  1. It would be great to be able to have 0 'Items', 1 "item", 2 "items". Rather than always "Item(s)"
  2. It would be also great to separately display the total cost in another span. Perhaps .cartAmount.

Upvotes: 1

Views: 159

Answers (1)

mkoryak
mkoryak

Reputation: 57958

try:

var text = $('#catCartSummary .cartSummaryItem').text();
items = text.match(/(\d+) item/);
var num = 0;
if(items &&items.length > 0){
   num = items[1];
}
$(".cartItems").html('<div class="cartitems">Shopping Cart <a href="#"><span class="cartTotal">'+num+'</span> Item'+(num == 1 ? '' : 's') +'</a></div>');

some pointers:

  • use .text() to not get any html in the text variable
  • use a regex to parse out the number of items instead of splitting

Upvotes: 1

Related Questions