Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
4.00/5 (1 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:

XML
<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

1 solution

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 ===)

JavaScript
$("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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900