November 30, 2010
Newbie stuck on a jQuery question…conditional statement
Question by flinx777
So I’m a complete newbie and stuck on a conditional statement. Here’s my code:
<script type="text/javascript">
$(document).ready(function(){
if($('span.fc_cart_item_price_total') == 0) {
$(span.fc_info).addClass('foo');
};
});
</script>
So I’m attempting to see if span with a class of “fc_cart_item_price_total” has a value of “0”, to then add a class of “foo” to the span with a class of “.fc_info”. This code above is not working. Here’s the HTML:
<span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
Here’s the other challenge I have. I’m trying to select the span with the value of “fc_info” before the span with the class of “fc_cart_item_price_total” but have no idea of how to just select this one span.
Answer by einaros
For each cart item whose price is $0.00, this will add the “foo” class to the preceding (and only the preceding) fc_info.
$(function() {
$(".fc_cart_item_price_total:contains($0.00)").each(function(i, n) {
(n=$(n)).prevAll(".fc_info:first").addClass("foo");
});
});
Answer by Starx
To make the above code working
<script type="text/javascript">
$(document).ready(function(){
if($('span.fc_cart_item_price_total').html() == 0) {
$(span.fc_info:first).addClass('foo');
};
});
</script>
And to select the first class fc_info
Use $(".fc_info:first")
as your selector