Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Friday 26 April 2013

How To Check If Specific Value Exist In Dropdown List Or Not

Today in this tutorial we will learn to check if a specific value exist in drop down list or not with the help of Jquery. Let’s start this with an example.

Example:-
Suppose a drop down or select list with id="ddlNames".

    <select id="ddlNames">
        <option value="1">Nancy Davolio</option>
        <option value="2">Andrew Fuller</option>
        <option value="3">Janet Leverling</option>
        <option value="4">Margaret Peacock</option>
        <option value="5">Steven Buchanan</option>
        <option value="6">Michael Suyama</option>
        <option value="7">Robert King</option>
        <option value="8">Laura Callahan</option>
        <option value="9">Anne Dodsworth</option>
    </select>

Now I want to check if the name “Rober King” exists in the dropdown or not?

Method 1:-

            var name = "Robert King";

            $('#ddlNames option').each(function () {
                if (this.text == name) {
                    alert("Exist")
                    return false;
                }
            });

In this method we use each loop to iterate through all the options and check if the specific text exists or not.

Method 2:-

var name = "Robert King";

if ($("select[id$='ddlNames'] option:contains('" + name + "')").length > 0) {
                alert("Exist");
            }

In this method contains() a built-in Jquery function is used to check if the specified text exist or not. By using same method you can check the value as well. Let me know in the comment section if you know better way to check if a value exist in a select list or not.

Hope it will be helpful for you.

3 comments:

  1. Thanks Amar,
    Very useful tutorial. Made my work really easy.

    ReplyDelete
  2. thanks,Great Tutorial.... :)

    ReplyDelete
  3. Thanks man, great help. :)

    ReplyDelete

Please do not enter spam links.