Search code examples
jqueryarraysfilterrestrict

Restrict number of selections and insert selected data into an array


I have 15 list items. I allow user to pick only 5 out of them. Then I put this info into the array and submit to the server.

<li><a href="#" id="item1" class="select">Item One</a></li> ... etc.

Then I use this code to toggle class of selected items

function SelectPrizes (){
$('a.select').click(function() {
    $(this).toggleClass("selected");
    $(this).text($(this).text() == 'Choose prize' ? 'Selected' : 'Choose prize');
    return false;
});
}

My question is, how to allow only 5 selections and add only selected items to an array by ID.

I understand that I can filter by hasClass('selected'), but I can't figure out the right syntax for that.


Solution

  • To answer your three questions:

    Allowing 5 selections: Make sure the length of $('a.select.selected') doesn't exceed your limit of 5:

    if ( $('a.select.selected').length < 5 ) {
        // Does not exceed, so we can add...
    }
    

    Add only selected items to array: just add only those items with the class 'selected':

    $('a.select.selected').each(function(){
        // Add to array
    });
    

    The syntax of hasClass('selected') as Mr. Disappointment suggested:

    if ( $(this).hasClass('selected') ) {
    
    }
    

    The solution of Mr. Disappointment will work if you allow the user to select more than 5 items and then select just any 5 of them.

    Also, a suggestion to improve your html. I assume the li items have a ul parent. Set the class 'select' to this ul parent and use the selector: $('ul.select li a').click().

    I've put this all together in a jsfiddle for you: http://jsfiddle.net/5b8aj/6/