Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
I am looking for a way to change the option value from a Asp ListItem control when users click on a link.
 
For example I have a Asp ListItem control:
 
<asp:DropDownList ID="DropDownList1" runat="server" class="Preview_link"
    Height="20px" Width="118px">
 
    <asp:ListItem>Red</asp:ListItem>
    <asp:ListItem>White</asp:ListItem>
    <asp:ListItem>Green</asp:ListItem>
    <asp:ListItem>Blue</asp:ListItem>
</asp:DropDownList>
And I have 2 links
<a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a>
When user clicks red the option will switch to red and white will switch to white. I am using the following code but it is not working.
 
How would I go about changing this jquery to work with a Asp listItem control instead of a <select>/<option>?
<pre lang="cs">jQuery("a.preview_link").click(function() {
var title = jQuery(this).attr("title");
jQuery(this).parent('p').find("select option").filter(function() {
    return $(this).text() == title;
}).attr('selected', 'selected');  });</pre>
Posted 3-Sep-12 5:35am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi there,
 
I can spot three problems that might be stopping this working. One is capitalisation and another is not trimming - both might stop your comparison. The other is not deselecting the currently selected option. The JavaScript should probably be as follows: (I have changed jQuery to the recommended/proper use of $ and changed == to recommended use of ===)
 
$("a.preview_link").click(function() 
{
    var dropDownListItems = $(this).parent('p').find("select option");
    var title = $(this).attr("title").trim().toLowerCase();
 
    dropDownListItems.filter(":selected").removeAttr("selected");
    dropDownListItems.filter(function() 
                     {
                         return $(this).text().trim().toLowerCase() === title;
                     })
                     .first()
                     .attr("selected", "selected");
});
 
Hope this works/helps,
Ed
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 3 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100