Rob Erskine
Rob Erskine

Reputation: 927

jQuery Conditional Statement using Int within a div

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

Upvotes: 2

Views: 222

Answers (5)

James Allardice
James Allardice

Reputation: 165941

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.

Upvotes: 4

Patricia
Patricia

Reputation: 7802

this should do it.

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

Upvotes: 0

rogerlsmith
rogerlsmith

Reputation: 6786

try -

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

Upvotes: -1

Galled
Galled

Reputation: 4206

Try with this:

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

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148514

$(document).ready(function() {

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

Upvotes: 0

Related Questions