I've seen a post about this somewhere in the forums where a requirement is to perform an autopostback on a dropdownlist, but only when a specific item is selected. Although there's different ways to approach this, I chose to use jQuery as the functionality needs to be performed strictly in the client-side. A regular Javascript function would be sufficient but jQuery makes this job a lot easier.
A markup example of a dropdownlist is below (HTML). Noticed that a CssClass attribute was added to the control. Since we're using a jQuery function, specifying a CssClass instead of locating the element by ID makes the implementation of the function more flexible. Whenever we want to use the same function, we can just add this particular class to any control or element that we wish (dropdownlist specifically). Another benefit is to make the Javascript unobstrusive as we're only storing a CSS attribute reference to the control and nothing else.
HTML:
1: <asp:DropDownList ID="ddlItems" runat="server" CssClass="doPostback">
2: <asp:ListItem></asp:ListItem>
3: <asp:ListItem>Selection1</asp:ListItem>
4: <asp:ListItem>Selection2</asp:ListItem>
5: <asp:ListItem>Selection3</asp:ListItem>
6: <asp:ListItem>Selection4</asp:ListItem>
7: </asp:DropDownList>
Once you've done the markup, all the work is performed in the Javascript tag where it finds all the dropdownlists that contains a Css that was specified above. See the code below for the function.
Javascript/jQuery:
1: <script type="text/javascript" language="javascript">
2: $(document).ready(function() {
3: // Forces the form to perform postback when a specific item in dropdownlist is selected
4: $('select.doPostback').change(function() {
5: if ($(this).val() == 'Selection4')
6: $('#Form1').submit();
7: })
8: });
9: </script>
In the above code, we are specifically doing a postback when Selection4 is selected and ignores every other selections. Since values are saved in the Viewstate, values within the controls in the form are remains in tact. If losing data is a main concern, then a good option is to have the form perform a save in the server-side code whenever a postback occurs.
- Dennis
menacestudio.com