![](/img/trans.png)
[英]How to get input.value in JavaScript when the “Enter” key is pressed if I have more buttons next to the input tag?
[英]Delete input.value when key is pressed
我的頁面上有一個 HTML 輸入。 用戶可以在其中輸入文本。 當他輸入我指定的命令並按 Enter 鍵時,頁面會將信息輸出到input.value
中。 如果用戶隨機輸入內容並確認他的輸入,頁面只會輸出:“未知命令。”,再次輸入到input.value
中。
我在這里做了一個條紋小提琴: JSFiddle
問題:
當我輸入: test
並按回車時,值變為: This is kind of working…
我知道要輸入新內容,但我首先必須突出顯示或刪除This is kind of working…
文本,這真的不直觀。
有沒有辦法改變我的腳本,這樣當我在輸入中並按下任何按鈕時,不是按鈕 Nr.13 又名“Enter”,頁面只是使輸入的值,按鈕,那個被壓了? 這樣用戶就可以在收到值后開始輸入新內容,而不必刪除我輸入的值。
我嘗試添加一個附加的.onkeypress function,但它破壞了一切,所以我沒有以正確的方式做到這一點。
這是我目前的 JS:
var clInput = 0;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
HTML:
<input id="inputMain" name="inputMain" autofocus>
我已經稍微更新了您的代碼,以完全按照您的意願行事。 基本上所做的是:
13 - Enter
的時間。13 - Enter
,請確保清除輸入。您可以在此處查看演示: https://jsfiddle.net/nh6c7ugf/
var clInput = 0; // Note: Ignore Upper- / Lower-Case in input?
var isEntered = false;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
// clear the value
if (isEntered) {
isEntered = false;
document.querySelector("#inputMain").value = '';
}
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
isEntered = true;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
抱歉,如果我不明白您要說什么,但如果您希望用戶可以在收到值后開始輸入新內容,而不必刪除您輸入的值。 你可以做
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
document.querySelector("#inputMain").selct();
}
這將 select 輸入字段的所有文本,當用戶輸入內容時,該字段的先前值將被刪除
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.