3

I want to programmatically check a checkbox and trigger the checkbox's onchange function

I have tried ("#myCheckbox").click() but it only checks it and does not call its onchange function

How can I get the onchange function to execute as well?

edit:

When the document is ready i need the checkbox checked and its on change function called programatically.

2
  • 3
    $('#myId').trigger('change'); Commented Oct 30, 2013 at 9:58
  • 2
    How is the onchange function defined? As an HTML attribute? Commented Oct 30, 2013 at 10:01

5 Answers 5

6

Your change listener needs to be set before you trigger the click on the checkbox. The following code works with no issues:

$("#myCheckbox").on('change', function(){
   console.log('Change'); 
}).click();

JSFiddle

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

Comments

2

How about something like this:

$('#myCheckbox').prop({ checked: true });
theOnchangeFunction();

$('#myCheckbox').on('change', theOnchangeFunction);

function theOnchangeFunction(){

}

4 Comments

I was typing something like this. This is the way to go!
+1 for the use of an object in the prop call. I didn't know about that!
@Archer I tend to use it in quite a lot of jQuery methods. .css() is another common use case, since you usually want to pass more than one property.
I knew about using it in css, but not in this way. Thanks for the eye-opener :)
1

you can try like below

 $("#scheck").attr('checked', 'checked').change();

it will check the check box as well trigger onchange event for checkbox

ex:

Script :

    $(document).ready(function () {
        $("#scheck").attr('checked', 'checked').change();
    });      

    function checkitout() {
        alert("onchange event fired");
    }

HTML :

    <input type="checkbox" name="tdcheck" id="scheck" onchange="checkitout();" />

Comments

0

Don't understand, it works : http://jsfiddle.net/FW5Lp/

<input type="checkbox" id="myc">
    <button id='clic'>click</button>

$('#myc').on('change', function(){alert('ca change');});

$('#clic').on('click', function(){$('#myc').trigger('click') });

Comments

0

Try both events by using on() like,

("#myCheckbox").on('click change',function(e){
    alert(e.type);
})

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.