Labanino
Labanino

Reputation: 3960

Toggling a class with jquery

Hi I want to toggle the on-off class but only one can be selected, something similar to a radio input:

$('.text-selection').on('click', function () {
    $(this).toggleClass('on-off');
});

This is my fiddle. Thanks.

Upvotes: 2

Views: 127

Answers (5)

Sushanth --
Sushanth --

Reputation: 55750

You need to remove the class 'on-off' for the other elements with the class '.text-selection' when any item is clicked.

$('.text-selection').on('click', function () {
    $(this).toggleClass('on-off');
    $('.text-selection').not(this).removeClass('on-off');
});

Check Demo

Upvotes: 1

Precastic
Precastic

Reputation: 4021

Add $('.point-and-click').removeClass('on-off'); as the first statement in your function

Upvotes: 1

Jude Osborn
Jude Osborn

Reputation: 1798

Remove the class from the selected item, and then add the class to the one that was clicked on:

$('.text-selection').on('click', function () {
    $('.on-off').removeClass('on-off');
    $(this).toggleClass('on-off');
});

JSFiddle

Upvotes: 2

Skarlinski
Skarlinski

Reputation: 2477

You can reset the ones already on before toggling them, like so:

$('.text-selection').on('click', function () {
    $('.text-selection').removeClass('on-off');
    $(this).toggleClass('on-off');
});

Upvotes: 1

Blender
Blender

Reputation: 298552

Just remove the class from the siblings of the current element:

$('.text-selection').on('click', function () {
    $(this).toggleClass('on-off').siblings().removeClass('on-off');
});

Demo: http://jsfiddle.net/MFQc9/4/

Upvotes: 2

Related Questions