8

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

Keavon
  • 6,837
  • 9
  • 51
  • 79
Sachin Verma
  • 3,712
  • 10
  • 41
  • 74

7 Answers7

13

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);
}
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
7

The selected answer will only work if the event listener is registered by setting the onchange property of the element.

If it is not the case, you can use:

    let element = document.getElementById('laneFilter');
    let event = new Event('change');
    element.dispatchEvent(event);
Uglylab
  • 103
  • 1
  • 6
7

This works for me and also triggers a change event:

const Chkinput = document.getElementById("laneFilter");
Chkinput.click();

(Tested in Chrome and Firefox)

mar10
  • 14,320
  • 5
  • 39
  • 64
0
<input type="checkbox" id="laneFilter"/>
<script> 
    checkbox = document.getElementById("laneFilter");
    checkbox.onclick = function(){ 
        alert('lol');
    };
    checkbox.checked = true;
</script>

should also work

schnawel007
  • 3,982
  • 3
  • 19
  • 27
0

In case someone else runs into this answer, the modern way to trigger a change event is by using the Event object.

    const checkboxElement = document.getElementById('highlightTables');

    checkboxElement.addEventListener('change', () => {
      console.log("something changed");
    });

    const event = new Event("change");
    checkboxElement.dispatchEvent(event);

See more information about this here.

ceiling cat
  • 496
  • 4
  • 12
-2

I cut it to 2 then work fine

$('#laneFilter').prop('checked','true');
$('#laneFilter').trigger('change');
Izzy
  • 6,740
  • 7
  • 40
  • 84
Amila
  • 37
  • 2
-4

Just call change function without parameters.

$('#laneFilter').change('change', function(){
        debugger
        ...
}).change();

it works in "jquery": "3.3.1"

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191