Check if previous clicked value is inside an array

Posted by Lelly on Stack Overflow See other posts from Stack Overflow or by Lelly
Published on 2012-09-11T20:31:49Z Indexed on 2012/09/11 21:38 UTC
Read the original article Hit count: 124

Filed under:

I have a list with different categories. All the list item are clickable. I want the user to pick between 1 and 3 items. They can toggle their choice, but maximum is alway 3. So far, so good.

Where it get tricky for me, is that I have some special categories that can't be combined with any others.

When a user click on one of these, all the other categories deselect and they can't add any other, (these item have only 1 category selection possible)

Exemple:

Let's say "Car" is a special category. If they click on Car, everything else deselect, Car is selected, and they can't select anything else. BUT they can click again on Car to deselect it, and from there the logic start over.

What's missing in my code is the part in bold just above this.

My code:

$j('.chooseCat li').on('click',function(){
   var $this = $j(this); //list item clicked
   var catId =  $this.children("a").attr("rel"); // list item id
   var specialCat = ['6','36','63']; 

   if ($this.hasClass("selected")) {
      $this.removeClass("selected");
      $j("#categorySuggestions p.error").hide("fast")
   } else {
      if( $j.inArray(catId, specialCat) !== -1  ) {
         $j('.chooseCat li').removeClass("selected");
         $this.addClass("selected");
      } else {
         if ($j('.chooseCat li.selected').length <= 2){
            $this.addClass("selected");
         } else {
             $j("#categorySuggestions p.error").show("fast").html("You cannot select any more categories");
         }
      }
   }
});

A working jsFiddle of where Iam at: http://jsfiddle.net/nfQum/9/

© Stack Overflow or respective owner

Related posts about jQuery