Javascript function to validate html select or drop down list

Introduction:

In my previous article I have explained about Code used to How to show confirmation message while deleting grid view row. In this article I am going to explain about how validate drop down list or html select using Javascript.
 
Explanation:
For the explanation purpose I have a select list which contains city list along with select city as items. While clicking on the button it will check the selected index of the select. If it is 0 then it will show the alert as city is not selected. Else it will show the message as city is selected.

Below is the code used.
<div>
    <select id=”selCity”>
        <option>Select City</option>
        <option>Chennai</option>
        <option>Mumbai</option>
        <option>Kolkatta</option>
        <option>Delhi</option>
    </select>
    <br/>
    <input type=”button” value=”Test” onclick=”return fnValidateDropDown();”  />
</div>
<script type=”text/javascript”>
    function fnValidateDropDown() {
        var obj = document.getElementById(‘selCity‘);
        if (obj) {
            if (obj.selectedIndex > 0 && obj.options[obj.selectedIndex].value != “-1”) {
                alert(‘City value is selected’);
                return true;
            }
            else {
                alert(‘City value is not selected’);
                return false;
            }
        }
        else
            return false;
    }
</script>
 
Check the demo here.
———————————–

—————————–

Do you like this article? Help us to improve. Please post your comments below.

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!