javascript onkeydownでテキストフォームに入力時の値が1回ずれて表示される

javascript onkeydownでテキストフォームに入力時の値が1回ずれて表示される

javascriptで、onkeydownでテキストフォームに入力時の値が1回ずれて表示される原因を掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 105.0.5195.127

実行コード

「onkeydown」を使用した以下のコードを実行すると、入力したデータが1つずつずれて表示されます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {    

    result.innerHTML = sample.value;

  }

  window.onload = () => {

    sample.onkeydown = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">

      <p id="result" class="bg-pink-500 text-white py-2 px-8 rounded-full mb-3 mt-4">入力された文字が表示される</p>

    </div>

    <div class="flex justify-center">

      <input id="sample" type="text"
        class="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">

    </div>

  </div>
</body>

</html>

実行結果

原因

これは、 「onkeydown」イベントは、キーを押す直前のテキストフォームの値を取得するためです。

対処法

「onKeyUp」イベントを使用します。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {    

    result.innerHTML = sample.value;

  }

  window.onload = () => {

    sample.onKeyUp = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">

      <p id="result" class="bg-pink-500 text-white py-2 px-8 rounded-full mb-3 mt-4">入力された文字が表示される</p>

    </div>

    <div class="flex justify-center">

      <input id="sample" type="text"
        class="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">

    </div>

  </div>
</body>

</html>

実行結果

また、「onkeydown」イベントも、キーを押す直前のテキストフォームの値が取得されます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {    

    result.innerHTML = sample.value;

  }

  window.onload = () => {

    sample.onkeydown = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">

      <p id="result" class="bg-pink-500 text-white py-2 px-8 rounded-full mb-3 mt-4">入力された文字が表示される</p>

    </div>

    <div class="flex justify-center">

      <input id="sample" type="text"
        class="shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">

    </div>

  </div>
</body>

</html>

実行結果