0

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

user1820851
  • 35
  • 1
  • 3

6 Answers6

1

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

Community
  • 1
  • 1
Felix
  • 36,929
  • 7
  • 39
  • 54
0

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

Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
0

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

Gautam3164
  • 27,319
  • 9
  • 56
  • 81
0

You could just pass the click like:

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

The demo.

xdazz
  • 149,740
  • 33
  • 229
  • 258
0

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.

Eru
  • 645
  • 4
  • 8
-2

Instead of do

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

you can just do:

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

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

  • I can't see why this answer is not useful, this works! Have you saw jsfiddle? – Alexandre TRINDADE Apr 22 '14 at 09:50
  • 1
    Triggering clicks is not a good practise. By doing it you emulate user 's behaviour and you should not be doing that. Also it's really a pain in the ass when you have to debug. – Eru Apr 22 '14 at 09:53