12

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

7 Answers 7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

10

This works for me and also triggers a change event:

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

(Tested in Chrome and Firefox)

1 Comment

Works. Smart. How didn't I think of that :D
9

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);

Comments

1

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.

Comments

0
<input type="checkbox" id="laneFilter"/>
<script> 
    checkbox = document.getElementById("laneFilter");
    checkbox.onclick = function(){ 
        alert('lol');
    };
    checkbox.checked = true;
</script>

should also work

Comments

-2

I cut it to 2 then work fine

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

1 Comment

The question said not to use jQuery.
-4

Just call change function without parameters.

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

it works in "jquery": "3.3.1"

1 Comment

The question stated explicitly not to use jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.