Joe Smth Joe Smth - 16 days ago 10
HTML Question

Display an alert when there are no values in the field

what I want to do is to show the user an alert when he presses the submit button, but there are no selected values in the category field. How can I do that?

<input type="submit" value="Search">

<div class="styleselect">
<select data-placeholder="Select a Category" name="cat" id="cat" class="select2" multiple >
<option value="all">All</option>
<option value="EN">England</option>
<option value="GR">Greece</option>
<option value="US">USA</option>
<option value="IT">Italy</option>
</select>
</div>

Answer

You can check if there any selected index on the select box, if no show the alert.

 function check()
   {
	 var values = document.getElementById('cat').selectedIndex;
	 if(values == '-1')
	 {
		 alert('PLease select atleast one'); 
		 return false;
	 }
   }
<input type="submit" value="Search" onClick="check()" >

<div class="styleselect">
                        <select data-placeholder="Select a Category" name="cat" id="cat" class="select2"  multiple >
                                  <option value="all">All</option>
                                 <option value="EN">England</option>
                                 <option value="GR">Greece</option>
                                 <option value="US">USA</option>
                                 <option value="IT">Italy</option>
                                </select>
                    </div>