フォーム内、入力フォームとセレクトボックスが1つずつあるのですが、2つの入力欄の内1つでも空白の状態で、「送信」ボタンを押した場合に、赤いテキストメッセージがフォーム付近に表示されるようにしたいです。
現状のコードでは、送信ボタンを押した際、セレクトボックスのみ空白の場合に赤いテキストメッセージが表示されるようになっています。
これを名前のフォームも空の場合(2つの入力欄の内どれか1つも空白の場合)に赤いメッセ―ジを表示させたいです。
回答よろしくお願いいたします。
html
1<!DOCTYPE html> 2 3<html lang="ja"> 4 5<head> 6 <meta content="text/html; charset=utf-8" /> 7 <meta name="viewport" content="width=device-width, initial-scale=1"> 8 9 <title></title> 10 11 <style> 12 13</style> 14 15</head> 16<body> 17 18<form action="a.php" method="post" id="form"> 19 20 21 <div class="auto-style2"> 22 23 24 <input type="text" class="name" name="name" id="name" placeholder="例)幸運太郎" value=""/> 25 26 <span class="selectbox1"> 27 <select id="age" class="age" name="age"> 28 <option value="">年代を選択する</option> 29 30 <option value="OO歳" >>OO歳 31 </option> 32 33 </select> 34 </span> 35 <div class="alert1">・必ず全て記入、選択して下さい!</div><!--赤いテキストエラーメッセージこの付近--> 36 </div> 37 38 39 <button type="submit" id="submit" name="submit" class="auto-style40" value="submit">送信 40 </button> 41 42 43</form> 44 45 46 47<script> 48 { 49 const 50form = document.getElementById('form'), 51inputs = [...form.querySelectorAll('input[type="text"]'), ...form.querySelectorAll('select')], 52Checker = (elm)=>{ 53const cls = (elm.nextElementSibling || elm.parentNode.nextElementSibling).classList; 54const flag = elm.value.trim() == ""; 55 56if(flag) cls.add('show1'); else cls.remove('show1');// javaでテキスト赤エラーメッセージの表示alert1 57 58return flag; 59}; 60 61 form.addEventListener('change', e=>{ 62 if(inputs.indexOf(e.target) >= 0) Checker(e.target); 63 }); 64 form.addEventListener('submit', e=>{ 65 if(inputs.map(e => Checker(e)).indexOf(true) >= 0) e.preventDefault(); 66 }); 67 } 68</script> 69 </body> 70 71</html>
/* セレクトボックスの位置 */ .auto-style2 { text-align: center; margin-top: 80px; background-color: white; } /* 出現文字show1 alert1 */ .alert1 { font-size: 0.85em; font-weight: bold; color: crimson; } .alert1 { visibility: hidden; } .alert1.show1 { visibility: visible; } .alert1.show1{ transform: translate(0px, 20px);/* 右側のpx上下調節 */ font-size: 20px; }
回答1件
あなたの回答
tips
プレビュー