How to Change the Selected Value of a <select> in Javascript and Raise the onchange Event

Posted by: Aaron Goldenthal 4/12/2009 5:07 PM

I had a project recently where I wanted to change the selected value of an ASP.NET DropDownList via Javascript and force a postback to trigger an UpdatePanel refresh.  Since AutoPostBack was set to true for the DropDownList, I expected the postback to occur automatically.  What I learned through this is that the select’s change event is only fired when the user changes the selection, not when it’s done through Javascript, so the postback never occurred.  After a little research, I learned you can call onchange explicitly, and that solved the problem.

Below is the final function, which accepts the ID of the DropDownList, the value to select (which was more readily available than the index to select), and a boolean flag indicating whether to fire the change event or not.

   1: function ChangeSelectByValue(ddlID, value, change) {
   2:     var ddl = document.getElementById(ddlID);
   3:     for (var i = 0; i < ddl.options.length; i++) {
   4:         if (ddl.options[i].value == value) {
   5:             if (ddl.selectedIndex != i) {
   6:                 ddl.selectedIndex = i;
   7:                 if (change)
   8:                     ddl.onchange();
   9:             }
  10:             break;
  11:         }
  12:     }
  13: }

In the process of working through this, I got a chance to check out the Javascript debugger in IE8, which everyone should take a look at (through the Tools menu > Developer Tools > Script tab).  It’s not perfect, but it’s definitely a step forward.

Tags: ,
Categories: Javascript
E-mail | Kick it! | DZone it! | Permalink | Comments (7) | Post RSSRSS comment feed

Comments (7) -

India sacchit 
9/16/2009 12:04 AM
Thanks -  Aaron saved some time on that!!

United States waggi 
11/14/2009 8:41 AM
Great post.

Spain Hector 
12/7/2011 7:01 PM
Thank you from Spain, you helped me a lot!

United States sana 
3/1/2012 9:50 PM
this is very usefull post for me i was thought like that but it was not clear to me thank you keep posting usefull techniques

United States Carol 
6/21/2012 9:04 AM
Thanks so much! Exactly what I needed!

Indonesia Daniel Robertus 
8/29/2012 1:08 AM
Daniel Robertus
Thank you.. nice reference..

United States Richard Sampson 
9/28/2012 11:14 PM
Richard Sampson
Great insight into the workings of the trusty list box!

The latest FF browser seems to handle this better if Line 8 of the function is revised to omit the "()" after ddl.onchange [not a function]

Thanks for sharing this code.