2

Hi Please check below code -

HTML

<div class="manage-user-freind" style="line-height:18px; cursor:pointer;">
  <span style="color:blue;">
    <img src="'+pageUrl+'/img/user-16x16.png" height="14" style="float:left; padding-top:2px;" /><input class="chk" type="checkbox" value="10" />pieter
  </span>
</div>

<div class="manage-user-freind" style="line-height:18px; cursor:pointer;">
  <span style="color:blue;">
    <img src="'+pageUrl+'/img/user-16x16.png" height="14" style="float:left; padding-top:2px;" /><input class="chk" type="checkbox" value="12" />john
  </span>
</div>

JQuery

$('.manage-user-freind').click(function(){
     $(this).toggleClass('clicked',function(){
            $('.chk').prop('checked', true);
     });
});

CSS

.clicked {
  background-color: yellow;
}

I have used toggleClass() function. toggleClass is working fine but all the check-boxes clicked also not unchecked the current checkbox .

I need when I will click any div first show that div in yellow color along with current checkbox checked. Again clicking on that yellow color div will remove and also checkbox will unchecked.

Thanks.

Sorry for my English wording. :(

4 Answers 4

5

Try this:

$('.manage-user-freind').on('click', function() {
    $(this).toggleClass('clicked').find('.chk').prop('checked', $(this).hasClass('clicked'));
});

Demo: https://jsfiddle.net/tusharj/d84z5vub/1/

Sign up to request clarification or add additional context in comments.

Comments

4

$.toggleClass don't have callback function. It's not async function, so you can move $('.chk').prop('checked', true); to next statement along toggling class:

$(this).toggleClass('clicked');
$('.chk').prop('checked', true);

2 Comments

This doesn't toggle the state of the checkbox
@Tushar yes, because OP is always setting checkbox as checked, not toggling it.
2

To check and uncheck, this code should work:

$('.manage-user-freind').click(function(){
     $(this).toggleClass('clicked');
     var checkbox = $(this).find('.chk');
     checkbox.prop('checked', !checkbox.prop("checked"));
});

Here is a Fiddle.

Comments

0

According to this: jquery function on toggleClass complete?

you can use premise to wait until class will be changed

$(this).toggleClass('clicked').promise().done(function(){
    alert('a');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.