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.