Jquery first click addClass selected second click removeClass selected

DD77 picture DD77 · Apr 20, 2012 · Viewed 7.9k times · Source

I got 4 options and I want to be able to select more than one option or remove the selected class with the second click.

Jquery

$('.contact-method li a').click(function(e) {
        $('.contact-method li a').removeClass('selected');
        $(this).parent('a').addClass('selected');
        e.preventDefault();
});

html

<ul class="contact-method">
<li class="sms"><a href="javascript:void(0);">SMS</a></li>
<li class="telephone"><a href="javascript:void(0);">Telephone</a></li>
<li class="email"><a href="javascript:void(0);">Email</a></li>
<li class="post"><a href="javascript:void(0);">Post</a></li>
</ul>

Demo http://jsfiddle.net/XeELs/97/

Answer

James McLaughlin picture James McLaughlin · Apr 20, 2012

Instead of

    $('.contact-method li a').removeClass('selected');
    $(this).parent('a').addClass('selected');

simply use

    $(this).toggleClass('selected');