1

I run some validation on my form when a checkbox is clicked, which works as intended.

$('#ilikeicecream').click(function(){
     runValidation();
});

The checkbox also has a label element, so I need to check for that as well. My first instinct was to do the following:

$('#ilikeicecream-label').click(function(){
     runValidation();
});

The problem is that the checkbox has not been checked at this point so validation does not work as intended. How can I get around this?

4 Answers 4

2

this should work for you...

$('#ilikeicecream').change(function(){
     runValidation();
});

$('#ilikeicecream-label').click(function(){
     if($('#ilikeicecream').attr('checked')){
          $('#ilikeicecream').attr('checked', false);
     }
     else{
          $('#ilikeicecream').attr('checked', true);
     }
     runValidation();
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just wrap the check-box with <label> tag. When you click label check-box will automatically change thus firing change event where you can invoke runValidation() function.

<label><input type="checkbox" value="1" id="blahblah" name="myname" /></label>

And keep the .change handler on check-box (you don't need separate one for its label)...

Comments

0

Use change():

$('#ilikeicecream').change(function(){
     runValidation();
});

For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.


I've tested in jsFiddle with the following code. I'm unable to provide a link however as jsfiddle is currently down.

<label for="ilikeicecream">sdsd</label><input id="ilikeicecream" type="checkbox" />

$('#ilikeicecream').change(function(){
     alert("test");
});

If this is not working, perhaps you have not specified the for attribute in your label to match the input.

3 Comments

That was also something I tried without success. Change doesn't seem to fire.
I've tested in jsfiddle and it works fine. Can you post your HTML?
@Beavis - If this is not working, perhaps you have not specified the for attribute in your label to match the input.
0
$('#ilikeicecream-label').click(function(){
     // Swap the checked property value of the check box here
     runValidation();
})

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.