Skip to content
Advertisement

check checkbox and trigger change event javascript

I want to trigger change event and check checkbox from javaScript not jQuery.
I am having issues with jQuery because of this Strange Behaviour.
What i used to do with jQuery is:

$('#laneFilter').prop('checked','true').trigger('change');

I want same to do with javaScript. This must be really simple but i could not find the way . please help thanks in advance

Advertisement

Answer

There’s a couple of ways you can do this. The easiest method is to just call that function:

var Chkinput = document.getElementById("laneFilter");
Chkinput .onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement