The Muffin Man
The Muffin Man

Reputation: 20004

Help with jQuery if statement

I have a paging system implemented for user comments and depending on which page you have clicked on I want to only show 3 page numbers in each direction. So if you clicked on page 6 then only show pages 2 - 9, so 7 total.

I have my html like so:

<div id="paging">
<span id="1" class="page"></span>
<span id="2" class="page"></span>
<span id="3" class="page"></span>
<span id="4" class="page"></span>
and so on...
</div>

jQuery/javascript like so:

$(".page").click(function() {
        var clicked = $(this).attr("id");

        var parent = $("#paging span");
        $(parent).each(function() {
            if($(this).attr("id")+ 3 >= clicked)
            $(this).removeClass("hidden");
            else
            $(this).addClass("hidden");
            });
});

So far all it does is apply the hidden class to any page numbers before the currently clicked one.

Upvotes: 1

Views: 138

Answers (2)

Neil
Neil

Reputation: 3231

Change your ids to be like 'P1', 'P2', etc. e.g.

<div id="paging">
    <span id="P1" class="page">A</span>
    <span id="P2" class="page">B</span>
    <span id="P3" class="page">C</span>
    <span id="P4" class="page">D</span>
    <span id="P5" class="page">E</span>
    <span id="P6" class="page">f</span>
    <span id="P7" class="page">g</span>
    <span id="P8" class="page">h</span>
    <span id="P9" class="page">i</span>
<!-- and so on... -->
</div>

Then change your javascript to:

$(".page").click(function() {
         var page_clicked = parseInt(this.id.replace(/^P/, ''));
         $(this).siblings('span').each(function() {
            var page_no = parseInt(this.id.replace(/^P/, ''));
            if((page_no >= (page_clicked-3)) && (page_no <= (page_clicked+3)))
                $(this).removeClass("hidden");
            else 
                $(this).addClass("hidden");
        });
}); 

or better still:

$(".page").click(function() {
         var page_clicked = parseInt(this.id.replace(/^P/, '')) - 1;
         var $pages       = $(this).siblings('span');
         var from         = Math.max(0,             page_clicked-3);
         var to           = Math.min($pages.length, page_clicked+3);

         $pages.addClass('hidden').slice(from,to).removeClass('hidden');
}); 

Upvotes: 1

SLaks
SLaks

Reputation: 887205

$(this).attr("id") returns a string.

You need to convert this string to a number by writing parseInt($(this).attr("id"), 10).

Upvotes: 3

Related Questions