-->

Android Chrome input onkeydown

2019-07-14 09:29发布

问题:

I have reduced this to the minimum code to show this problem. The problem is that this works fine on Chrome on my computer, but on Chrome on my Android, it doesn't work properly. First, the highly simplified code:

<html><head><script language='javascript'>
function kd(e) {
  inp = document.getElementById('myinput');
  if(inp.value=='example') inp.value='';
  return true;
}
</head><body>
  <input type='text' id='myinput' value='example'
  onkeydown='return kd(event);'>
</body></html>

On my computer, I put the cursor in the box that says example. I press any key. The word "example" goes away and whatever letter I pressed appears.

Now, on Android/Chrome, I put the cursor in the box that says example. I press any key. The word "example" goes away, but the letter I pressed does not appear. If I press another key, it will show that letter. I can keep typing. It simply refuses to show the first letter I press.

This apparently has to do with the value='' part of the javascript. If I comment out that line, it works fine (but doesn't erase the word "example" when pressing the first key).

Update: I tested this on an iPhone. It shows the letter of the first keypress properly. So, this is limited to either Android or Android's Chrome.

回答1:

Clear the text on input focus

$('input').val('');

and its better practice to use keyup event since users tend to drag their fingers on the keyboard you want make sure you get what they intended