Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9004

JavaScriptで入力チェックする方法(修正版)

$
0
0
スペースが入ると入力チェックを通過してしまうのと、入力漏れメッセージを配列に変えたほうが良いとのアドバイスを頂きましたので修正いたします。また修正前の記事でタグに誤りがあったのを発見したのでその部分も修正済みです。修正前の記事も勉強のため残します。 <!DOCTYPE html> <html lang="ja"> <style> body { padding:50px; background-color: greenyellow; } body #title { color:red; font-size : 50px; } body #name { width:200px; } body #mail { width:400px; } body #button1 { background-color: blue; } </style> <head> <meta charset="utf-8"> <title>sample</title> </head> <body> <h1 id = "title">送信フォーム</h1> <form action = "index4.html" method="POST"> Name:<input type="text" id="name"><br> Mail:<input type="email" id="email"><br> Detail:<textarea id="detail" value="detail" cols="50" rows="3" maxlength="150"></textarea><br> year:<select id = "year"> <option value="2021" id="2021">2021年</option> <option value="2022" id="2022">2022年</option> <option value="2023" id="2023">2022年</option> </select> month:<select id = "month"> <option value="1" id="1">1月</option> <option value="2" id="2">2月</option> <option value="3" id="3">3月</option> <option value="4" id="4">4月</option> <option value="5" id="5">5月</option> <option value="6" id="6">6月</option> <option value="7" id="7">7月</option> <option value="8" id="8">8月</option> <option value="9" id="9">9月</option> <option value="10" id="10">10月</option> <option value="11" id="11">11月</option> <option value="12" id="12">12月</option> </select> <input type="button" id="button1" value="送信" onclick="func1()"> </form> <div id="div1"></div> <script language="javascript" type="text/javascript"> //変数の定義 const name = document.getElementById('name'); const mail = document.getElementById('email'); const detail = document.getElementById('detail'); const button1 = document.getElementById('button1'); //入力チェック処理 const func1 = () => { const unfilledItems = []; if(name.value.replace(/\s+/, '').length === 0) { unfilledItems.push('名前'); } if(mail.value.replace(/\s+/, '').length === 0) { unfilledItems.push('メールアドレス'); } if(detail.value.replace(/\s+/g, '').length === 0) { unfilledItems.push('詳細'); } if(unfilledItems.length > 0) { alert(`${unfilledItems.join('、')}が入力されていません。`); } else { if (window.confirm('送信してもよろしいですか?')) { div1.innerText = `Name:${name.value}、Mail:${mail.value}、Detail:${detail.value}、year:${year.value}、month:${month.value}`; } } } </script> </body> </html>

Viewing all articles
Browse latest Browse all 9004

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>