ngplayground
ngplayground

Reputation: 21667

jquery toggling a checkbox

I've been at this for the past 2 hours and cannot get this figured out.

I have a list item that when clicked the jquery pulls the class of the li item which is a color. It then Capitalizes the first letter then finds the checkbox value with the color matching and marks it as checked.

Only I want it so that if someone clicks the li item again it will uncheck the checkbox

Can someone help at all?

$('#colours li').live('click', function (){
    var color = $(this).attr('class');
    color = color[0].toUpperCase() + color.slice(1);
    console.log($('input[value="'+color+'"]'));
    $(this).css('opacity','0.5');

    if($('input[value="'+color+'"]:checked').length) {
        $('input[value="'+color+'"]').attr('checked', true);
        console.log("checked");
    } else {
        $('input[value="'+color+'"]').removeAttr('checked');
        console.log("not checked");
    }    
});



<ul id="colours">
        <li class="black"></li>
        <li class="brown"></li>
</ul>

<input type="checkbox" name="color" value="Black" class="hidden" />
<input type="checkbox" name="color" value="Brown" class="hidden" />

forgot to add the ul and inputs are loaded using jquery .load()

Upvotes: 0

Views: 266

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50808

When you remove the attribute, you're taking it out of the DOM, literally. You just want to toggle the checked property. Some changes to note.

.live() is deprecated; I've replaced it with the proper .on() call.

.attr() is deprecated in almost all cases, in favor of .prop(). I've replaced this as well.

We don't need to check the length, we need to check if the element is checked. jQuery provides an .is() with a psuedo-selector of :checked.

$(document).on('click', '#colours li',  function() {
    var color = $(this).prop('class');
    color = color[0].toUpperCase() + color.slice(1);
    $(this).css('opacity', '0.5');

    $('input[value="' + color + '"]').prop('checked', function(i,oldVal){
        return !oldVal;
    });

});​

Upvotes: 2

mreq
mreq

Reputation: 6542

this should do

$('#colours').on('click', 'li', function (){
  var th = $(this);
  var color = th.attr('class');
  color = color[0].toUpperCase() + color.slice(1);
  var input = $('input[value="'+color+'"]')
  console.log(input);
  th.css('opacity','0.5');

  if(input.length == 1) {
    if (input.is(':checked')) {
      input.prop('checked', false);  
      console.log("not checked");
    } else {
      input.prop('checked', true); 
      console.log("checked");
    }
  }

});

Upvotes: 1

Related Questions