bappa147
bappa147

Reputation: 539

How to display a number of div elements on selecting a drop down box?

Suppose:

 <select id="itemsPage">
    <option value="1">12 items per page</option>
    <option value="2">View All</option>
    </select>

and there number of div elements like:

<div class="item first">
                            <img src="../img/products/doll_170.jpg" alt="Doll" />
                            <p class="headline">Sale!</p>
                            <p class="itemName">Snowboard Outfit + Gear</p>
                            <p class="itemPrice"><span class="was">$28</span> $22</p>
                            <p class="rating"><span class="five"></span></p>
                            <p class="backordered">Backordered until Dec. 18, 2012</p>
</div>

now there are 20 items like this. i want to display 12 items when i select "12 items per page" and want to display all 20 items when i select "View All" from the drop down box.

Upvotes: 1

Views: 1492

Answers (4)

Patryk Studniak
Patryk Studniak

Reputation: 1

There's probably some easier way, but I just wrote some code what should work for sure.

This function takes the number of items to show per page, and an array of items on which to operate. The first loop makes all elements invisible, and the following loop makes the first few visible again (the remainder remaining invisible).

function hideAllListElems(list) {
        list.classList.add('hideList');
    }

function showListElems(list) {
        list.classList.remove('hideList');
    }

function showList(start, end) {
    var listsDomElements = document.querySelectorAll('#list li');
    var i;
    start = start || 0;

    hideAllListElems();
    for(i = start; i < end; i++) {
        showList(listDomElements[i]);
    }
}

Upvotes: 0

Anil Saini
Anil Saini

Reputation: 637

Try this code to implement the required functionality -

$('body').on('change', '#itemsPage', function(){
 $('div.item').hide(); //first hide all elements
 if($(this).val() == 1){
    $('div.item:lt(12)').show(); //12 to display first 12 elements of one kind
 }else{
    $('div.item').show();
 }
});

Check it on fiddle - Click for demo

Upvotes: 2

Mark S
Mark S

Reputation: 3799

You need to get <select> value on change() event then check if the value == 1 show 12 items, and if value == 2 show all 20 items.

$('#itemsPage').change(function () {
    var val = $(this).val(),
        $item = $('.item');

    if (val == 1) {
        $item.eq(11).nextAll().hide();//item index higher than 12 will be hidden
    } else if (val == 2) {
        $item.show();//show all 20 items 
    }
})

Check this jsfiddle.

Upvotes: 1

Ted Johnson
Ted Johnson

Reputation: 4343

Please select them with jquery and then:

http://api.jquery.com/length/

or

http://api.jquery.com/size/

They seem equivalent. Not sure if you have a larger event issue. Let us know.

Upvotes: 0

Related Questions