Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

javascript - How to simulate typing in input field using jQuery?

What I want is to simulate typing in <input> field using javascript.

I have the following code:

var press = jQuery.Event("keydown");
press.ctrlKey = false;
press.which = 65;
$("#test").trigger(press);

But when I load the page, the #test input field has no typed characters, the keycode of '65' represents 'A', but there is no 'A' input.

Basically what I want is to automatically typing in the website using Greasemonkey.

Please give me some ideas or some library with which I can use to do this.
Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can send key events, and anything listening for them will get them, but they will not change the input, so you will not see the letter A appear, for example. This is mostly a security thing; see "Manually firing events" for a discussion about that.

So, if you want the letter to appear, you must alter the input's value as you send the key event. There is a jQuery plugin for that, see "The $.fn.sendkeys Plugin".

You can see how an <input> reacts with user-applied keys, key events, and that plugin at this jsFiddle.

For reference, this is the key piece of code from that jsFiddle:

$("button").click ( function (zEvent) {
    if (zEvent.target.id == "simA_plain") {
        console.log ("Send Plain key event");
        var keyVal = 65;
        $("#eventTarg").trigger ( {
            type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
        } );
    }
    else {
        console.log ("Use the Plugin to simulate a keystroke");
        $("#eventTarg").sendkeys ("B") ;
    }
} );


That plugin should be sufficient if you are just trying to "simulate typing on an <input>". However, depending on what you are really trying to do, you may need to do one or more of the following:

  1. Just set the text to what you want it to be.
  2. Send a keydown event, if the page's javascript triggers off of that.
  3. Likewise, send a change event, etc., if the page's javascript triggers off of that.
  4. Just find and call the page's javascript directly. Use script injection, the location hack, unsafeWindow, and/or @grant none mode to do that.
  5. Something else? State your true objective and link to the target page.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...