0

I'd like to create a function to check and uncheck checkboxes when we click on the previous span element, it works one time but it doesn't work a second time... I don't understand...

My html code :

<form class="form" action="#" method="post">
  <label>Input radio</label>
  <span>Text</span><input type="checkbox">
  <span>Text</span><input type="checkbox">
  <span>Text</span><input type="checkbox">
  <label>Input checkbox</label>
  <span>Text</span><input type="radio" name="radio">
  <span>Text</span><input type="radio" name="radio">
</form>

My js code :

$('form.form').find('span').on('click', function(){
    $this = $(this);
    if( $(this).next().attr('type') == 'checkbox' ){ 
        if( $this.next().is(':checked') ){
            $this.next().attr('checked', false);
        }else{
            $this.next().attr('checked', true);
        }
    }else{
        $this.next().attr('checked', true);
    }
});

Update 1

URL : http://jsfiddle.net/tonymx227/bvPsq/

Anthony

2 Answers 2

2

You have to use prop() for that

$this.next().prop('checked', false);

The reason it works the first time is because jQuery changes the attribute, and the checkbox is updated, but the checked property of the element is not updated, and that it was jQuery uses internally to see if the checkbox is checked, so the next time you try to change it, the attribute says it's checked, and the checkbox appears to be checked, but jQuery thinks it's not checked as that is what the property is saying, as it wasn't set with attr().

FIDDLE

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

Comments

1

This is where you can use a label, wrap your inputs with a label. You don't necessarily need to use Javascript for this.

<label>Text<input type="checkbox" /></label>

or you can use label for if you have check boxes with id associated with it.

<label for="chk1">Text</label> <input type="checkbox" id="chk1" />

Demo

The HTML Element represents a caption for an item in a user interface. It can be associated with a control either by using the for attribute, or by placing the control element inside the label element. Such a control is called the labeled control of the label element.

1 Comment

Yes I know that but I didn't want to use this method ;-) Thank you anyway !

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.