2

So, my question in it's most basic form:

<div id="total"> 0 </div>

and what I'm hoping to accomplish with jQuery:

$(document).ready(function() {
  if ("#total" > 2){
    /*do something*/
  }   
});

I feel like this should be something relatively easy, but the syntax is escaping me. Any help would be extremely helpful. Thanks!

Rob

5 Answers 5

4

You can use the text method to get the text of an element, and parseInt to get a Number from that:

if(parseInt($("#total").text(), 10) > 2) {
    //Do something
}

Here's a working example.

Note how the selector (#total) is passed into jQuery ($(selector)). In your question you have the correct selector, but it's just a string, so your if statement would compare the string "#total" to the number 2.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh okay great, thanks so much. I really appreciate the explanation as well. This may be an entirely different question, but if #total goes over 2 at any time, the event should be triggered correct?
@RobErskine, No, this event will only be triggered if #total is greater than 2 on document.ready.
Thanks Xyan. Is there a way to make it update if the int changes?
Figured it out - I threw the conditional statement within a mousedown function. Thanks everyone for the help again
0
$(document).ready(function() {

     if (parseInt($.trim(("#total").text()),10) > 2){
         /*do something*/
    }   
});

1 Comment

You shouldn't need the trim as parseInt doesn't care about spaces.
0

Try with this:

$(document).ready(function() {
     if (parseInt($("#total").text()) > 2){
         /*do something*/
    }   
});

Comments

0

this should do it.

if(parseInt($('#total').text()) > 2){
   //do something.
}

Comments

-1

try -

if (("#total").val() > 2)

2 Comments

As #total is a div element it won't have a value property which is what val returns.
Won't work for divs. The .val() method is primarily used to get the values of form elements such as input, select and textarea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.