Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tampermonkey: Trigger event does not work for element

I'm trying to add some functionality using Tampermonkey on top of a providers angular application but I'm stuck at this simple thing. I can't replicate the issue using CodePen so we're going to have to go for theories and suggestions. I'll try to be as specific as I can.

Adding this interval when the page loads to check when an input with the id serialNumberInput is available. Then I'm adding a dropdown to the form, and attach an onChange event to it to update the serial input field with the value of the selected option. However, the trigger parts just never happens. It does work when I enter them manually, but not with the script.

var populateSerialNumbersTimer = setInterval(function(){

    var serial = $("input#serialNumberInput");

    if($(serial).length >= 1){

        $(serial).css("display", "inline").css("width", "50%");
        $(serial).after(deviceToSerialSelectionHTML);

        $("select#deviceToSerial").on("change", function(){
            $(serial).val($("select#deviceToSerial").val());
            $(serial).trigger("change");
            $(serial).trigger("blur");

        });

        clearInterval(populateSerialNumbersTimer);
    }
}, 200);

enter image description here

I've thought about it and considering how the serial number ends up in the text field the field must be accessible. Maybe it's that the events that I'm trying to trigger has not been declared at the time of the function declaration?

Suggestions much appreciated.

like image 586
PatrikJ Avatar asked Jan 27 '26 06:01

PatrikJ


1 Answers

It looks like jQuery tries to cache the event somehow. This is how I solved it with native javascript in case someone else is interested:

function triggerEvent(e, s){
    "use strict";
    var event = document.createEvent('HTMLEvents');
    event.initEvent(e, true, true);
    document.querySelector(s).dispatchEvent(event);
}

$("select#deviceToSerial").on("change", function(){

    serialNumberInput.val($("select#deviceToSerial").val());

    triggerEvent("change", "input#serialNumberInput");
    triggerEvent("blur", "input#serialNumberInput");

}
like image 54
PatrikJ Avatar answered Jan 29 '26 20:01

PatrikJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!