开发者

Using jQuery to add up values and then fire a result

I'm attempting to take the different values in a list, add them up and if the values are greater than 150, a class is added to a specified div. Here's the HTML I'm working with:

<ul class="fc_cart_item_options">
<li class="fc_cart_item_option fc_cart_item_weight">Weight: 70 <span class="fc_uom_weight">LBS</span></li>
<li class="fc_cart_item_option fc_cart_item_weight">Weight: 81 <span class="fc_uom_weight">LBS</span></li>
</ul>

What I'm trying to figure out is how, using jQuery, do I add u开发者_StackOverflowp the values of these different list items shown above, and when they're greater than 150 to then add a class to a specific div? There may be instances where I only have one list item that has a weight great than 150 whereas in some cases I may have 20 list items that add up to greater than 150 and therefore need the same outcome which is to add a class to a specific div.

My goal is that if the above list item's values is ever greater than 150, the div with the class of "gt_150" will get the class of "foo" added on. Hope that makes sense.

======

Edit:

Just ran into a small problem after getting some great answers from others (thanks again so much everyone for your immediate responses).

One thing I didn't take into account is quantity. Here's what I mean: a list item may be 70 pounds, but may have a quantity of 3 (210 pounds) which pushes it over the weight limit. The problem is with the current solution, this doesn't take into account quantity of a given list item. This solution (first response provided below) works great, but I forgot to factor the following.

<table>
<tr class="fc_cart_item">
<td>
    <ul class="fc_cart_item_options">
    <li class="fc_cart_item_option fc_cart_item_weight">
    Weight: 70 <span class="fc_uom_weight">LBS</span>
    </li>
    </ul>
</td>
<td class="fc_cart_item_quantity">3</td>
</tr>
</table>

In this HTML above, a list item may only be 70 pounds by itself (which doesn't cause the jQuery to add the class "foo" to the specific div), but if the quantity is 3, I need to factor that in.

In all cases with the list item, the next cell with the quantity will follow right after it.


$('.fc_cart_item').each(function() {
  var total = 0;
  $(this).find('.fc_cart_item_weight').each(function() {
     var weight = parseInt($(this).text().split(' ')[1]);
     total += weight;
  });

  var qty = parseInt($(this).find('.fc_cart_item_quantity').text());
  total *= qty;
  if(total > 150)
    $('.gt_150').addClass('foo');
});


You can use a regexp to grab all the numbers in one go, and then calculate the sum:

var total = 0;
$.each($(".fc_cart_item_options").text().match(/\d+/g), function(i, v) {
   total += +v;
});

if (total > 150) $('.gt_150').addClass('foo');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜