tonymx227
tonymx227

Reputation: 5451

Check and uncheck a checkbox using jquery

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

Upvotes: 0

Views: 103

Answers (2)

adeneo
adeneo

Reputation: 318342

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

Upvotes: 2

PSL
PSL

Reputation: 123739

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.

Upvotes: 1

Related Questions