【JavaScript】入力した名前と姓を結合して表示させよう!
今回のテーマ
JavaScriptで入力した名前と姓を結合してフルネームとして
表示させるプログラムを作成してみる。
作成したコード
index.html
<!doctype html> <html lang="ja"> <head> <meta charset="utf-8"> <title>テスト</title> </head> <body> <div class="name_container"> <label>姓<input type="text" class="text" id="familyName"></label> <label>名<input type="text" class="text" id="lastName"></label> </div> <p id="fullName"></p> <script src="app.js"></script> </body> </html>
app.js
const familyName=document.querySelector('#familyName'); const lastName=document.querySelector('#lastName'); const fullName=document.querySelector('#fullName'); familyName.addEventListener('keyup',()=>{ KeyDisplay(); }); lastName.addEventListener('keyup',()=>{ KeyDisplay(); }); const KeyDisplay =()=>{ const family=familyName.value; const last= lastName.value; fullName.innerHTML=family+" "+last; }
コードの詳細
jsから詳しく見てみる。
まずはそれぞれの要素を取り出す。
const familyName=document.querySelector('#familyName'); const lastName=document.querySelector('#lastName'); const fullName=document.querySelector('#fullName');
次にfamilyNameとlastNameの要素に対してkeyupのイベントを追加する。
keyupというのはキーボードから何かしら文字を入力し、キーボードから
離した際に発行するイベントのことです。
イベント発生時に後ほど記載するKeyDisplayのメソッドを起動します。
familyName.addEventListener('keyup',()=>{ KeyDisplay(); }); lastName.addEventListener('keyup',()=>{ KeyDisplay(); });
KeyDisplayを定義します。
それぞれvalueから入力した文字を取得します。
最後にその取得した値をinnerHTMLを使って表示させます。
const KeyDisplay =()=>{ const family=familyName.value; const last= lastName.value; fullName.innerHTML=family+" "+last; }
まとめ
今回は基本的なDOM要素を取得した操作で作成した。 基礎的であるが、HTMLのどの要素を取得しているかを意識していきたいです。