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
151 views
in Technique[技术] by (71.8m points)

javascript - Programmatically sending keys to input field?

I'm coding a web-portal for a set top box with a custom keyboard.

The keyboard has most of the standard character keys but no backspace!

Since there are some other free custom keys, I would like to map one of these to backspace when I'm in an input field or in a text area.

The question is: How do I programmatically send a backspace to the input field?

Or for that matter: How do I programmatically send any key (like an arrow key) to the input field?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Assuming the browser supports the W3C event model, you can create a KeyEvent and dispatch that using the dispatchEvent method of the input field. There's an example (using MouseEvent) over on mozilla.org. There are also some more links over where I last answered this question ;-)

UPDATE: the following code has been tested in Firefox 3.5, and successfully backspaces through the characters in the text field:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

window.onload = function() {
    var field = document.getElementById("foo");
    var button = document.getElementById("bar");
    button.addEventListener("click", function(event) {
        var keyEvent = document.createEvent("KeyboardEvent");
        keyEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0);
        field.dispatchEvent(keyEvent);
    }, false);
}

</script>

</head>
<body>
<div>
<input type="text" id="foo" value="abcdef">
<button id="bar" type="button">Fire key event</button>
</div>
</body>
</html>

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

1.4m articles

1.4m replys

5 comments

57.0k users

...