Aaron Goldenthal

Sometimes ASP.NET is Rocket Science

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

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.

Comments (7) -

  • sacchit

    9/15/2009 5:04:49 PM |

    Thanks -  Aaron saved some time on that!!

  • waggi

    11/14/2009 12:41:47 AM |

    Great post.

  • Hector

    12/7/2011 11:01:21 AM |

    Thank you from Spain, you helped me a lot!

  • sana

    3/1/2012 1:50:55 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

  • Carol

    6/21/2012 2:04:06 AM |

    Thanks so much! Exactly what I needed!

  • Daniel Robertus

    8/28/2012 6:08:42 PM |

    Thank you.. nice reference..

  • Richard Sampson

    9/28/2012 4:14:34 PM |

    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.

Comments are closed