3

I'm new to jquery and has some problems with the following code, the code is trying to replace the class of an item when clicked, the first part works as expected. If the item has a class of none it adds featSelected, however if i then click again to deselect it, it does not add the class of none. Any ideas would be appreciated, be gentle as i am in the throws of learning jquery(from book, looking at some courses though!).

 <script type="text/javascript">
          $('li span[id^="feat"]').click(function(){
          if ($(this).hasClass('none')) {
              $(this).addClass("featSelected") 
            }

            else if ($(this).hasClass('featSelected')) {
              $(this).addClass("none") 
            }

    })

    </script>

Any help would be appreciated.

Jason

Jason Congerton
  • 750
  • 2
  • 9
  • 23

3 Answers3

1

Your code is just adding the new class name. You also have to remove the old class name:

$('li span[id^="feat"]').click(function(){
    if ($(this).hasClass('none')) {
        $(this).removeClass("none");
        $(this).addClass("featSelected");
    } else if ($(this).hasClass('featSelected')) {
        $(this).removeClass("featSelected");
        $(this).addClass("none");
    }
});

But based on what you are doing, you can just use toggleClass on both of them:

$('li span[id^="feat"]').click(function(){
    $(this).toggleClass("none featSelected");
});

EDIT: I noticed your code was missing semicolons at the end of statements. I added them in in my examples above, and for future reference, you should always use semicolons to end statements in javascript.

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • The toggle class looks the best way, but it does not work? Is it because i have to already set up the class to show users what is already selected please see html; – Jason Congerton Nov 28 '11 at 10:53