Question

I have a checkbox with onChange event and a button who check and uncheck this checkbox. The event is fired when I check and uncheck manually. But when I press on the button to change the status of the checkbox no event is fired.

You can see the exemple here : http://jsfiddle.net/7Nws8/7/

<input type="checkbox" id="1">
<input type="button" id="2" value="click">

Do you have ideas to fire the event onchange when the button is pressed.

regards

Was it helpful?

Solution 2

You can use $("#1").trigger("change") to trigger change event and to toggle click prop("checked", !$("#1").prop("checked") .Try this:

 $(document).on("click","#2",function()
 {
   $("#1").trigger("change").prop("checked", !$("#1").prop("checked"));
 });
 $(document).on("change","#1",function()
 {
  alert("changed")
 });

Working Demo

OTHER TIPS

You need to trigger the change event after setting the checked state of your checkbox:

$(document).on("click","#2",function()
{
    if($("#1").is(":checked") == true)
    {
         $("#1").prop('checked', false).change(); // or .trigger('change')
    }
    else
    {
        $("#1").prop('checked', true).change(); // or .trigger('change')
    }
})

Updated Fiddle

Also note that id start with number is not valid HTML. You can refer here for more informations

Just add trigger

$(document).on("click","#2",function(){

    if($("#1").is(":checked") == true) { 
       $("#1").prop('checked', false); 
    } else {
       $("#1").prop('checked', true);
    }
    $('#1').trigger('change');
});

See this FIDDLE

You could just pass the click like:

$(document).on("click","#2",function()
{
    $('#1').click();
});
$(document).on("change","#1",function()
{
    alert("changed");
});

The demo.

Trigger the event after changing the property value:

$(document).on("click", "#2", function () {
    var checkboxEl = $('#1');
    checkboxEl.prop('checked', !checkboxEl.is(":checked")).change()
});

$(document).on("change", "#1", function () {
    alert("changed");
});

It's also good to cache the jQuery object.

Instead of do

 $("#1").prop('checked', false);

you can just do:

 $("#1").click();

JsFiddle: http://jsfiddle.net/hWhg3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top