Search code examples
javascriptjquerytampermonkey

How can I use JS to fill out a simple input field when the ".value = ***" doesnt seem to be recognized?


Every day I have a "health and fitness" steps tracker that needs to be entered at work. I am trying to use TamperMonkey to automate most of it. However, I am having trouble getting the input field to validate my "value".

enter image description here

I execute the console command:

document.getElementById("self-enter-steps-input").value = 3000;

which yields:

enter image description here

However, when I hit "Save" manually, I get the following error:

enter image description here

If I hit "Save" programmatically, the window closes but the number doesnt register. If I hit "backspace" or type an extra "0" manually, the entire field gets validated and it saves the whole value if I hit submit.

I've also tried entering the value as a string i.e.

document.getElementById("self-enter-steps-input").value = "3000";

The field gets validated but the value doesn't get recorded. A simple backspace or extra number typed manually does, however, make the entire field record.

I've tried some simulated "keypress" events with no success. Im a JS newbie so any help is appreciated.


Solution

  • You might need to trigger a change listener manually by dispatching a change event manually:

    const steps = document.getElementById("self-enter-steps-input");
    steps.value = "3000";
    const change = new InputEvent('change', { bubbles: true });
    steps.dispatchEvent(change);
    

    By the looks of it the validation of the input happens on either change, blur (or alternatively focusout because blur won't bubble), or input. Please check your developer tools for which event is actually being listened, and adjust the code I gave accordingly.