Skip to content Skip to sidebar Skip to footer

Remove Class On Click And Deselect Input With Jquery

I have a list item with a radio button input in each, on click of the list item the input is checked. However, if clicked again I want to remove the class and deselect the option.

Solution 1:

  $('ul.top-options li input[type=radio]').click(function() {
     if(!$(this).closest('li').hasClass('active')){
         $('ul.top-options li').removeClass('active');
         $(this).closest('li').addClass('active');
     }else
         $(this).removeAttr('checked').closest('li').removeClass('active');
});

http://jsfiddle.net/BKgdc/8/

Solution 2:

You need to have an event handler :

$('ul.top-options input').change(function(){
    if ($('ul.top-options input').length) {
        $('ul.top-options li').each(function(){ 
            $(this).removeClass('active');
        });
        $('ul.top-options li input:checked').each(function(){ 
            $(this).parent('li').addClass('active');
        }); 
     }
});

but your code can be simplified as

$('ul.top-options input').change(function(){
     $('ul.top-options li').removeClass('active');
     $('ul.top-options li input:checked').parent('li').addClass('active');
});

See demonstration

Solution 3:

$(document).ready(function() {

    $li = $('ul.top-options li');
    $li.click(function() {
        if(!$(this).hasClass('active')){
        $li.removeClass('active')
        .filter(this).addClass('active').find('input').prop('checked', true);
        } else {
            $(this).removeClass('active');
            $(this).find('input').prop('checked', false);
        }
    });
    $li.filter(':has(:checked)').click();

});

Solution 4:

Your solution would be to use checkboxes instead of radio buttons. No need for any javascript when using checkboxes.

If you want to deselect a radio button you should remove it's selected attribute. :checked only applies on checkboxes.

Solution 5:

You would likely need to do this:

$li = $('ul.top-options li');
$li.click(function () {
    varself = $(this);
    $li.not(self).removeClass('active');
    (self.hasClass('active') ? (self.removeClass('active').find('input').prop('checked', false)) : (self.addClass('active').find('input').prop('checked', true)));
});
$li.filter(':has(:checked)').click();

alternate conditional form:

$li = $('ul.top-options li');
$li.click(function () {
    varself = $(this);
    $li.not(self).removeClass('active');
    if (self.hasClass('active')) {
        self.removeClass('active').find('input').prop('checked', false);
    } else {
        self.addClass('active').find('input').prop('checked', true);
    }
});
$li.filter(':has(:checked)').click();

a fiddle to show in action: http://jsfiddle.net/ZK4th/

Post a Comment for "Remove Class On Click And Deselect Input With Jquery"