JDT
JDT

Reputation: 13

Exactly the same javascript but one isn't working?

I wanted to create a checklist that would move a slider as the user ticked boxes. I found the following 2 pieces of code:

http://jsfiddle.net/t2nvft7q/

$(document).on('click', '.checkBoxLeft', function () {
  if ($(this).find('input[type="checkbox"]').is(':checked')) {
    $(this).removeClass('checked').addClass('not-checked');
    $(this).find('input[type="checkbox"]').attr('checked', false);
  } else {
    $(this).removeClass('not-checked').addClass('checked');
    $(this).find('input[type="checkbox"]').attr('checked', true);
  }
});

And then I found this which is more like what I want to do and based on the first one: http://jsfiddle.net/ezanker/UznQe/

But on the second one if you click one of the boxes, untick it and then tick it again it stops working?

As far as I can tell it's because of that bit of code above. I've commented out things and moving them around to see what runs first, I've tried replacing parts of the second fiddle with the first and as far as I can tell the only difference between the html / css is the second has a value field on the checkboxes but editing this doesn't have any effect.

Could someone point out what I'm missing?

Upvotes: 1

Views: 73

Answers (2)

Wesley Smith
Wesley Smith

Reputation: 19571

You should use .prop, but for the check itself I would just use .hasClass()

Since the code already gives the clicked element the class of checked, there's really no reason to look any deeper than the clicked element which you already have as $(this).

See this working example:

    $(document).on('click', '.checkBoxLeft', function () {
        if ($(this).hasClass('checked')) { // here use `.hasClass()` for the check 
            $(this).removeClass('checked').addClass('not-checked');
            $(this).find('input[type="checkbox"]').prop('checked', false);
        } else {
            $(this).removeClass('not-checked').addClass('checked');
            $(this).find('input[type="checkbox"]').prop('checked', true);
        }

        //  .....


    });

Upvotes: 0

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

You shouldn't use .attr to set the checked property, use .prop instead. .attr is for setting attribute on the element, and .prop is for settings properties.

Example (JSFiddle):

if ($(this).find('input[type="checkbox"]').is(':checked')) {
    $(this).removeClass('checked').addClass('not-checked');
    $(this).find('input[type="checkbox"]').prop('checked', false);
} else {
    $(this).removeClass('not-checked').addClass('checked');
    $(this).find('input[type="checkbox"]').prop('checked', true);
}

Upvotes: 2

Related Questions