Here, in this article I’ll show you how to use jQuery methods to check if a user has selected any value from an HTML select element. The principle however, remains the same for an Asp.Net DropDownList control.
In the markup section, I have added a HTML <select> option and add few values to it. In addition, I have a button control of type submit. When a user clicks the button, the jQuery script will validate the selection.
<html> <head> <title>jQuery Validation for select option</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head> <body> <p>Clicking the submit button without selecting an item from the list will show a message.</p> <select id="selBooks" name="books"> <option value=""></option> <option value="Stategies Unplugged">Stategies Unplugged</option> <option value="jQuery Reference">jQuery Reference</option> <option value="HTML5 Fundamentals">HTML5 Fundamentals</option> <option value="Popular Science">Popular Science</option> </select> <input type="submit" id="submit" value="Submit" /> </body> <script> $(document).ready(function () { $("#submit").click(function () { var books = $('#selBooks'); if (books.val() === '') { alert("Please select an item from the list and then proceed!"); $('#selBooks').focus(); return false; } else return; }); }); </script> </html>
For every click, the above script will check the value selected by the user. It would return false if they do not select any value and will set focus back on the <select> element.
Select a Default Value From the <select> element
This is optional. It is just an example and it might help in some scenarios.
The idea is to select a default value from the list of options in the <select> element, if the user is reluctant not to select any value at all.
Simply add the line (in itallic) in the above condition, instead of setting focus on the <select> element.
if ($('#selBooks').val() === '') { alert("Please select a book and then proceed.");$('#selBooks').focus();// ADD THIS LINE. $('#selBooks').val('jQuery Reference'); return true; }
I have tried to keep this simple. This tip is for beginners, who are learning the basics of jQuery and this is useful for form submission process. However, don’t forget to write a script using code behind procedures, for data validation, if you are submitting the data in a database.