Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the first n number of elements in jQuery?

I have a page that has 50 elements with the same class "fields" which are all display none at the moment

<div class="fields" style="display:none;">
    ...
</div>
<div class="fields" style="display:none;">
    ...
</div>
<div class="fields" style="display:none;">
    ...
</div>
<div class="fields" style="display:none;">
    ...
</div>
...

How to I only show the first 3 or whatever number. Plus count them with a count on top like the following example below.

So for example if I needed the first 3 this is what i need the divs to look like

<div class="fields">
    <h1>Station 1</h1>
</div>
<div class="fields">
    <h1>Station 2</h1>

</div>
<div class="fields">
    <h1>Station 3</h1>
</div>
<div class="fields" style="display:none;">
    ...
</div>
...

So basically only some the number of divs that I need...I already have the number of elements I need to show in this blur statement in the station_count variable. Also notice i need a span tag with the count..any ideas on how to do this

    $("#number_station").blur(function(){
        var station_count = $(this).val();
                    //code goes there
    });
like image 549
Matt Elhotiby Avatar asked Oct 16 '11 13:10

Matt Elhotiby


1 Answers

How to I only show the first 3 or whatever number.

$('div.fields:lt(3)').show();

Plus count them with a count on top

$('div.fields:lt(3)').each(function (index)
{
    $('<h1></h1>', {text: 'Station ' + index}).prependTo(this);
}).show();

Demo: http://jsfiddle.net/mattball/TssUB/


Read the jQuery API docs for basic questions like this:

  • :lt() selector
  • .prependTo()
  • jQuery() (for creating new elements)
like image 162
Matt Ball Avatar answered Oct 22 '22 11:10

Matt Ball