简体   繁体   English

输入字段始终提示输入而不是显示占位符文本

[英]input field always prompts for input rather than showing placeholder text

I have an input box that a user types into: 我有一个input框,用户可以input

<input id="entry" type="text" onkeypress="BeginTest(event)" placeholder="To start the test, begin typing here." class="focus"> 

And in this entry box everything they type will get stored in a variable, but then cleared when they hit space or enter. 并且在此输入框中,他们键入的所有内容都将存储在变量中,但是当它们敲入空格或回车时将被清除。

var entry = document.getElementById("entry");

function BeginTest(event) {
  if (event.which == 32 || event.which == 13) {
    //store entry.value or do whatever
    entry.value = "";
  }
}

The problem is when they enter in something new in the entry box, the entry box is already a space in before they type. 问题是当他们在输入框中输入新内容时,输入之前输入框已经是空格。 So if I execute: 所以,如果我执行:

  1. Type "abcd" in entry box 在输入框中输入“ abcd”
  2. Hit space 命中空间

I would then have to hit a backspace now to see the entry.placeholder text that is there. 然后,我现在必须单击一个退格键才能看到其中的entry.placeholder文本。 How do I make it not include that space whenever a space or enter key is hit? 每当按下空格或Enter键时,如何使它不包括该空格?

It is also quite annoying because I have to currently use the entry.value.trim() to remove the beginning space. 这也很烦人,因为我当前必须使用entry.value.trim()删除开始的空格。

Catch keyup instead of keypress , then make sure you cancel the processing of the keystroke, so it's not added to the empty value after your handler completes. 捕获keyup而不是keypress ,然后确保取消对击键的处理,因此在处理程序完成之后,不会将其添加到空值中。

 var entry = document.getElementById("entry"); function BeginTest(event) { if (event.which == 32 || event.which == 13) { entry.value = ""; event.stopPropagation(); event.preventDefault(); return false; } } 
 <input id="entry" type="text" onkeyup="BeginTest(event)" placeholder="To start the test, begin typing here." class="focus"> 

The space is there because the character doesn't get added to the input's value until after your event listener is called. 出现空格是因为在调用事件侦听器之前,字符不会添加到输入的值中。 If you were to cancel the event the character won't get added. 如果要取消事件,则不会添加角色。

event.preventDefault();

http://plnkr.co/edit/KDcvkXZ1dyxpNPcw8i9D?p=preview http://plnkr.co/edit/KDcvkXZ1dyxpNPcw8i9D?p=预览

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM