CdnXxRRODxX
CdnXxRRODxX

Reputation: 341

Automatically enter text into an input box with simulated keypresses

I have a form that detects keypresses to validate whether the user has entered any data into the input boxes (I can't change the form, I'm just accessing it).

I wrote an app that automatically changes the value property of an input box with the appropriate data, however, the form always fails to submit because there weren't any keypresses when the input box was selected and it wants me to "enter data" into the input box.

Is there a way that I can select the input box, enter a random character via a "keypress" right before I change the value?

I need a completely Javascript solution, I've seen some solutions that might work in JQuery, but I'm unable to load that library for this particular project.

Upvotes: 1

Views: 140

Answers (1)

Phil
Phil

Reputation: 2084

I have no idea if this will do what you want, but it does seem to be running the "onkeypress" alert().

<input type="text" id="blah" value="" onkeypress="javascript:alert ('Key Pressed');" />

<script type="text/javascript" language="Javascript">
    // Create a keyboard event based on the function allowed by the browser (initKeyboardEvent or initKeyEvent)
    var e = document.createEvent ("KeyboardEvent");
    if (e.initKeyboardEvent)
    {
        e.initKeyboardEvent("keypress", true, true, window, false, false, false, false, 0, 65);
    }
    else if (e.initKeyEvent)
    {
        e.initKeyEvent("keypress", true, true, window, false, false, false, false, 0, 65);
    }

    // Focus the input and send the keypress
    var inp = document.getElementById("blah");
    inp.focus ();
    inp.dispatchEvent(e);
</script>

Upvotes: 1

Related Questions