7

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,036
  • 8
  • 48
  • 74
Sachin Verma
  • 3,544
  • 9
  • 35
  • 70

6 Answers6

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
  • 7,819
  • 9
  • 46
  • 75
5

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
  • 73
  • 1
  • 5
1

This works for me and also triggers a change event:

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

(Tested in Chrome and Firefox)

mar10
  • 13,235
  • 5
  • 37
  • 62
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,848
  • 3
  • 16
  • 22
-1

I cut it to 2 then work fine

$('#laneFilter').prop('checked','true');
$('#laneFilter').trigger('change');
Izzy
  • 6,510
  • 5
  • 37
  • 76
Amila
  • 39
  • 2
-4

Just call change function without parameters.

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

it works in "jquery": "3.3.1"

Yevgeniy Afanasyev
  • 32,743
  • 20
  • 155
  • 172