alex
alex

Reputation: 11

How to compare two values with jquery?

i have to get them via a selector and add a class.

<div class="count_1">
<span class="percentage">10 %</span>
</div>
<div class="count_2">
<span class="percentage">90 %</span>
</div>


if (parseInt($(".count_1.percentage").value) > $(".count_2.percentage").value)) {
            blabla
        }

Upvotes: 1

Views: 13097

Answers (3)

Alexander
Alexander

Reputation: 1

it's working, but i have multiple votingresult on the page. i am calling the script everytime with a pollid as a selector. but it's working only for the first pollresult. any suggestions?

if (parseInt($(".pollid_1 .count1 .percentage").html(), 10) > parseInt($(".pollid_1 .count2 .percentage").html(), 10))
$(".pollid_1 .count1 span.percentage").addClass("selected");
else
$(".pollid_1 .count2 span.percentage").addClass("selected");

<div class="pollid_1">
<div class="count_1">
<span class="percentage">10 %</span>
</div>
<div class="count_2">
<span class="percentage">90 %</span>
</div>
</div>



if (parseInt($(".pollid_2 .count1 .percentage").html(), 10) > parseInt($(".pollid_2 .count2 .percentage").html(), 10))
$(".pollid_2 .count1 span.percentage").addClass("selected");
else
$(".pollid_2 .count2 span.percentage").addClass("selected");

<div class="pollid_2">
<div class="count_1">
<span class="percentage">10 %</span>
</div>
<div class="count_2">
<span class="percentage">90 %</span>
</div>
</div>

and so on...

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53931

Something like this. It would be better to use IDs for the wraper divs though ...

var val1 = parseInt ( $( '.percentage:first', $( '.count_1' ) ).html (), 10 );
var val2 = parseInt ( $( '.percentage:first', $( '.count_2' ) ).html (), 10 );

if ( val1 > val2 ) {
    // do stuff
}

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129792

This should do:

if (parseInt($(".count_1 .percentage").html(), 10) > parseInt($(".count_2 .percentage").html(), 10))

Note that the space in the selector denotes child elements. .count_1.percentage matches elements with class="count_1 percentage", wheareas .count_1 .percentage matches class="percentage" within class="count_1"

Also note the need to wrap both values in parseInt, and I also added a second parameter to the parseInt call which explicitly parses in base 10.

parseInt('08', 10); // 8
parseInt('08'); // 0

Upvotes: 5

Related Questions