4
3

More than 3 years have passed since last update.

入力した文字をリアルタイムで反映させる方法

Last updated at Posted at 2020-05-13

個人的メモです
フォームに入力した文字を反映させる方法

📗 完成形

14d0bba3e8c58537da2713088cc039ca.gif

📗 コード

HTMLの構造

  <form id="form_test">

    <div id="input_value_box"></div>   //inputされた情報が入る場所

    <input type="text" name ="input_value" value="">
 </form>
jsファイル
//inputに入力したらdivタグに文字が反映される


const formTestInputValue = document.forms.form_test.input_value; //document.formsでformの中身を取得,さらに後ろの記述で細かく指定できる


formTestInputValue.addEventListener('input',()=>{     //formTestInputValueにinputがされたら
  let inputValueBox  = document.getElementById('input_value_box');//input_value_boxのidを検索して
  inputValueBox.textContent = formTestInputValue.value  //inputValueBoxのtextcontentにformTestInputValueのvalueをくっつける
})

📗 おまけ【文字じゃなくて入力数を表示したいとき】

3aa0260a7a089112401821da3e9934d4.gif

JSの一番下の出力の最後にlengthとつけると文字数をカウントしてくれます。

inputValueBox.textContent = formTestInputValue.value.length
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3