0

I have a simple quiz in which user can answer multiple questions, now when the user checks the box I am adding a class for the background.

Here is jsfiddle:demo

Here is function

    // here we add event handler for newly created checkboxes.
    nextQuestion.find("input[type='checkbox']").on('change', function () {

      if ($(this).is(":checked")) {

        //add checkbox background when is checked
        $(this).addClass("input-before");

        //uncheck the checkbox if another checkbox is checked
        $('#next').prop("disabled", false);
        $('input.cb').not(this).prop('checked', false, function(){
          //remove the background ...this is not working
          $(this).removeClass("input-before");
        })

      } else {
        $('#next').prop("disabled", true);
        $(this).removeClass("input-before");
      }
    });

Now when user check another checkbox the other checkbox is unchecked but the background is still there\

I want to remove the background when Unchecked.

what do I need to change to get this working?

6
  • it's working fine in your fiddle link Commented Dec 13, 2019 at 14:31
  • 2
    @Utkarsh The blue highlight around the unchecked box is still showing in the fiddle for me. OP, I'd consider changing your approach to this. You can do this entirely in CSS using the checked selector Commented Dec 13, 2019 at 14:32
  • @Utkarsh there is still a blue background showing, that is my problem Commented Dec 13, 2019 at 14:34
  • The code at the moment is quite messy. You are giving styling to the checkbox according to :checked property or "input-before" class. Try to unify this for now to have both - the tick and the background for the same 'state' and choose if you want this to be a class or a :checked state. Avoid mixing both of them. Commented Dec 13, 2019 at 14:38
  • @WojciechDynus that is why I needed help, I am stuck Commented Dec 13, 2019 at 14:40

1 Answer 1

1

You can iterate through checkbox to add and remove the background class as given below

nextQuestion.find("input[type='checkbox']").on('change', function () {
    .....

    $("input[type='checkbox']").each(function () {
               if (this.checked) {
                    $(this).addClass("input-before");
               }else{
                     $(this).removeClass("input-before");
               }
    });  

    ......  

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

1 Comment

No problem.. happy to help :)

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.