1

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.

CdnXxRRODxX
  • 341
  • 5
  • 14

1 Answers1

1

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>
Phil
  • 2,008
  • 1
  • 17
  • 23
  • This code makes sense but I can't seem to get it to work. It's within a chrome extensions which I didn't think made a difference in this case, but maybe that's why it's not executing? No errors or anything either... – CdnXxRRODxX May 18 '16 at 01:59
  • Oh. I've never developed a Chrome extension before to know about its quirks. A quick Google search reveals: http://stackoverflow.com/questions/13987380/how-to-to-initialize-keyboard-event-with-given-char-keycode-in-a-chrome-extensio where someone says there's a Webkit bug, so that might be related? Sorry I can't help more :( – Phil May 18 '16 at 02:06
  • If the extension is not for release to the public, have you considered writing it as a Userscript? That might allow you to do what you want and would work with any browser that supports them (eg. Chrome with Tampermonkey extension, Firefox with Greasemonkey, etc). – Phil May 18 '16 at 02:07
  • Seems like that bug might be the cause, I'll mention the Userscript. I'm just helping out some other developer so I'm not sure if it needs to be an extension. Thanks for the help! – CdnXxRRODxX May 18 '16 at 02:12