Programmatically press "Left" key in a text input
I am trying to programmatically fire a key event to go left in a text box, but not having any luck.
The input element has focus and the cursor is at the end. I'm trying to get the cursor to move left one step - before the letter "F" *programmatically by firing a Keyboard event (keydown/keyup/keypress) with the corresponding keystroke ← or → targeted at the input box.
ABCDEF|
Here's the code so far:
HTML
<input id="a" type="text" />
Javascript
var keyEvent = document.createEvent("KeyboardEvent");
var keyLocation = '0x00';
var keyIdentifier = "Left";
keyEvent.initKeyboardEvent("keypress",
true,
true,
window,
keyIdentifier,
keyLocation,
false);
$("a").dispatchEvent(keyEvent);
Saved a quick de开发者_StackOverflowmo on jsfiddle if you want to see the whole code - http://jsfiddle.net/Vsafv/
I am not interested in making this cross-browser (just get it working in Chrome).
e = jQuery.Event("keydown"); // define this once in global scope
e.which = 37; // Some key value
$("input").trigger(e);
where "input" is your textarea
37 - left
38 - up
39 - right
40 - down
So when you record your "events" you record the values for the keys pressed.
I'm sure you already figured out a way to do this but just in case, here's an idea of how i would tackle it:
var keysPressed = new Array(); // somewhere in the global scope
$("input").keydown(function (e) {
keysPressed.push(e.which); //adding values to the end of array
});
Hope this helps
And for those not viewing jQuery as the solution to everything :)
From http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
As far as I can see, you can do:
var pos = document.getElementById("a").length;
document.getElementById("a").setSelectionRange(pos-1, pos-1);
精彩评论