Barlas Apaydin
Barlas Apaydin

Reputation: 7315

JS triggered checkbox's checked attr doesn't dynamically change

My problem is really simple, i have a hidden checkbox and a custom fake checkbox which triggers the real one. I've tried lots of various methods but click function works only at the begining than stops.

I've and searhed alike questions on stackoverflow but coun't find a problem which similar to mine. Thank you for your time.

Here is jsFiddle.

html:

<div class="fl">
    <span class="tri_checkbox"></span>
    <input class="hidden_checkbox" type="checkbox" />
</div>

jQuery:

$(document).on('click','.tri_checkbox',function() {
  if ( !$(this).hasClass('selected') ) {
    $(this).parent().find('input.hidden_checkbox').attr('checked','checked');
    $(this).addClass('selected');
  }else{
    $(this).parent().find('input.hidden_checkbox').removeAttr('checked');
    $(this).removeClass('selected');
  }
});

Upvotes: 0

Views: 113

Answers (3)

Alex
Alex

Reputation: 10216

  • Dont use if (!hasClass) {} else {}, make it in the right logic in the first place! :)
  • .parent().find() = siblings()
  • use .prop()

.

$(document).on('click','.tri_checkbox',function() {
          if ( $(this).hasClass('selected') ) {
            $(this).siblings('input.hidden_checkbox').prop('checked', false);
            $(this).removeClass('selected');
          }
        else {
            $(this).siblings('input.hidden_checkbox').prop('checked', 'checked');
            $(this).addClass('selected');
          }
    });

fiddle

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Shorten your code up and try this:

$(this).toggleClass("selected");
$(this).parent(".fl").find(":checkbox").prop("checked", $(this).hasClass("selected"));

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

Or just use one big chain:

$(this).toggleClass("selected").parent(".fl").find(":checkbox").prop("checked", $(this).hasClass("selected"));

Big chain: http://jsfiddle.net/CVWWn/5/

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use .prop() to set the checked property

$(document).on('click', '.tri_checkbox', function () {
    $(this).next().prop('checked', function (_, checked) {
        return !checked;
    });
    $(this).toggleClass('selected');
});

Demo: Fiddle

  1. You can use .next() here since the span and the input are siblings
  2. Use toggleClass() to change the class

Read: Attributes vs. Properties

Upvotes: 4

Related Questions