Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery trigger change event on checkbox

Is it possible to trigger change event on a checkbox using javascript/jquery?

Something like this (I run triggerChange on click of a button):

<label><input type="checkbox" id="chk"/>Label for chk</label>

<script>
function triggerChange(){
    $("#chk").trigger("change");
}
</script>

When I run the above code I get this error: "trigger is not a function".

like image 435
Zelter Ady Avatar asked Apr 17 '13 09:04

Zelter Ady


People also ask

How do you trigger a checkbox to change the event?

To trigger a checkbox click event even if it's checked with jQuery, we can call the jQuery trigger method with 'click' . Then we can cal trigger with 'click' by writing: $('input').

Is checkbox checked jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


3 Answers

That trigger is not a function error message indicates something else is at play. According to this SO question:

What happens when a jQuery selector wasn't found?

no.good.at.coding says:

Do note however that you must ensure that selector is a jQuery object! Otherwise, you could get an error indicating that "trigger is not a function".

It's likely that you have forgotten jQuery?


As for your implementation, you should be fine the way you are using it. But trigger should be used to trigger event methods on elements that have already been attached via jQuery. Check out my demo:

Fiddle:
With click event: http://jsfiddle.net/fS4R5/1/
Without click event: http://jsfiddle.net/fS4R5/2/

HTML:

<label><input type="checkbox" id="chk"/>Label for chk</label> 

JS:

function triggerChange(){     $("#chk").trigger("change"); }  $("#chk").change(function() {    alert("triggered!");  });  triggerChange(); 
like image 81
Jace Avatar answered Oct 06 '22 03:10

Jace


In jQuery, you can usually trigger an event by calling it's eventhandler method withoud any function parameters.

For example a click handler can be assigned as such:

$('#mything').click(function(e){dostuff});

the click event in itself can be triggered by simply running: $('#mything').click();

I suspect this can be done for every existing event in jQuery.

like image 24
Joachim VR Avatar answered Oct 06 '22 03:10

Joachim VR


Be sure that Input of Type checkbox is enabled, in case is disabled trigger will not fire event

//fire event 
$('#ceckBoxId').click();
$('#ceckBoxId').trigger('click');

or change checkbox checked val

$('#ceckBoxId').prop('checked', true);
$('#ceckBoxId').prop('checked', false);
like image 25
Alex Avatar answered Oct 06 '22 03:10

Alex