実現したいこと
プルダウンの選択フォームの選択がない場合にエラーメッセージを表示したい
前提
Laravelで商品登録ページを作成していて、
メーカーを選択するプルダウンの選択をせずに登録しようとするとエラーメッセージを表示させるコードをjavaScriptを使って書いたのですが、
エラーが出てしまいます。
どなたか詳しい方アドバイスお願いいたします。
発生している問題・エラーメッセージ
main.js:1 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at main.js:1:35
該当のソースコード
<div class="form_frame"> <form method="post" id="newForm" action="{{route('post.store')}}" enctype="multipart/form-data"> @csrf <ul> <li> <div> <label for="product">商品名<span>*</span></label> <input type="text" id="product" name="product" value="{{old('product')}}"> @error('product') <div class="error">{{$message}}</div> @enderror </div> </li> <li> <div> <label for="brand">メーカー名<span>*</span></label> <select id="brandSelect" name="brand_id"> <option velue="" selected disabled >メーカー名</option> @foreach ($categories as $category) <option value="{{$category->id}}">{{$category->brand}}</option> @endforeach </select> <div id="selectErrorMessage"></div> </div> </li> <li> <div> <label for="price">価格<span>*</span></label> <input type="number" id="price" name="price" value="{{old('price')}}"> @error('price') <div class="error">{{$message}}</div> @enderror </div> </li> <li> <div> <label for="stock">在庫<span>*</span></label> <input type="number" id="stock" name="stock" value="{{old('stock')}}"> @error('stock') <div class="error">{{$message}}</div> @enderror </div> </li> <li> <div> <label for="pic">商品画像</label> <input type="file" id="pic" name="image_path" value="{{old('image_path')}}"> </div> </li> <li> <div> <label for="comment">コメント</label> <textarea id="comment" name="comment" value="{{old('comment')}}"></textarea> </div> </li> </ul> <div class="btn-section"> <button class="entry-btn" type="submit">新規登録</button> <button type="button" onclick="history.back()" class="return-btn">戻る</button> </div> </form>
document.getElementById("newForm").addEventListener("submit", function(event){ let selectedValue=document.getElementById("brandSelect").value; if(!selectedValue){ document.getElementById("selectErrorMessage").textContent="メーカー名は必須です"; event.preventDefault(); }else{ document.getElementById("selectErrorMessage").textContent=""; } });
試したこと
スペルミスがないか確認して、
いろいろ調べたのですが、全く進まず、、