alexkodr
alexkodr

Reputation: 543

toggleClass on label, disable until unclicked

I have some checkboxes which when you click disable all other checkboxes until you untick the checked box. This is working great. But i also want to incorporate a toggleClass 'active' on the labels.

So when you click a label it adds class active. But if you click another label it doesn't add class active until you un-toggle the class off the previously clicked label. Sorry if that sounds a little confusing.

I have the js working for the checkboxes part here:

$('.test').change(function(){
if($('input.test').filter(':checked').length == 1)
    $('input.test:not(:checked)').attr('disabled', 'disabled');
else
    $('input.test').removeAttr('disabled');
});

and i have the toggleClass for the label

$('.holder label').click(function() {
    $('.holder label').not(this).removeClass('active')
    $(this).toggleClass('active')
})

But they somehow need to work together. You'll get a better idea by checking out this fiddle http://jsfiddle.net/CHQsR/327/

e.g. if you clicked 'Label1' its correct (text goes bold and checkbox is ticked). But if you click 'Label2' that should add 'active' class (and go bold) until you uncheck 'Label1'

Thanks

Upvotes: 0

Views: 154

Answers (1)

andrew
andrew

Reputation: 412

Take a look at fixed version: http://jsfiddle.net/maestrow/uqy77q98/3/

Html:

<div class="holder">
    <label for="checkone">Label1</label>
    <input type="checkbox" class="test" id="checkone" />
</div>

<div class="holder">
    <label for="checktwo">Label2</label>
    <input type="checkbox" class="test" id="checktwo" />
</div>

<div class="holder">
    <label for="checkthree">Label3</label>
    <input type="checkbox" class="test" id="checkthree" />
</div>

Javascript:

$('.test').change(function(){
  if($('input.test').filter(':checked').length == 1)
    $('input.test:not(:checked)').attr('disabled', 'disabled');
  else
    $('input.test').removeAttr('disabled');  

  var id = $(this).attr('id');
  $('label[for='+id+']').toggleClass('active');
});

Css:

.active{font-weight:bold;}

Actually you shoud not care about clicking on labels, as they wired with corresponding checkboxes by for atrribute. On checkbox change, along with disabling/enabling rest checkboxes, you should toggle class on corresponding label.

Also you shouldn't include hash symbol in id tags. Hash used in selectors, when you want select by id, i.e.: <div id="mydiv"> and selector to select this div is #mydiv, which you can use as $('#mydiv').

Upvotes: 1

Related Questions