Selecting a dropdownlist by text using Jquery filter() API

It is a small issue i came across recently.  I was using a dropdownlist in asp.Net mvc which was populated using $.ajax call. I need to select the item in dropdownlist if  it’s text is “SearchText”.

It seems simple using Contains  API from Jquery. but if the text is not available in the data source it throws javascript exception when we try to select the item.

There is an easy way of doing the check and selecting the text in dropdownlist.

.Filter() – Jquery API


$('#MyList option').filter(function() {

return ($(this).text() == searchText);

}).attr('selected', 'selected');

Here, For each item the text will be compared and returned true only when an exact match is found. if  searchText is empty also it will not throw any exception while setting the attribute.

Code really seems very easy and handy. This anonymous method syntax is nothing new to C# developers.

I hope its useful!

Advertisements

About saxenapraveen

I work with Microsoft and have 12 years of experience in developing,designing and leading reliable and scalable solutions for cloud and device ready businesses.

Posted on February 27, 2012, in .NET and tagged , , . Bookmark the permalink. 2 Comments.

  1. Good post Praveen!. Simple and elegant solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: