Reputation: 21
I have a c# web user control with an asp drop down list. I want to use jquery or similar to set the selected value based on the url of the website.
<asp:DropDownList ID="LangSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="LangSelect_SelectedIndexChanged" >
<asp:ListItem Text="English" Value="English"> English</asp:ListItem>
<asp:ListItem Text="Français" Value="Français"></asp:ListItem>
<asp:ListItem Text="Español" Value="Español"></asp:ListItem>
<asp:ListItem Text="Deutsch" Value="Deutsch"></asp:ListItem>
</asp:DropDownList>
I have tried this:
<script>
if (window.location.href.indexOf('de') > 0) {
$("#LangSelect").val('Deutsch');
}
</script>
However, its giving an error:
Uncaught TypeError: Cannot read property 'val' of null
Upvotes: 0
Views: 79
Reputation: 46
$(document).ready(function () { if (window.location.href.indexOf('de') > 0) { $('<%=LangSelect.ClientID%>').find('option[value='Deutsch']').prop('selected', true);
}
});
Upvotes: 0
Reputation: 7867
Use document ready to make sure your DOM is loaded, and use LangSelect.ClientID
to get the LangSelect
ID for HTML markup that is generated by ASP.NET.
$(document).ready(function () {
if (window.location.href.indexOf('de') > 0) {
$('#<%= LangSelect.ClientID %>').val('Deutsch');
}
});
Upvotes: 1
Reputation: 168
The problem is your selector, first, you're missing the #
at the start to indicate it's an ID, but even then, your element is set runat="server"
which will change the actual ID of the html element when the page is rendered.
For this you can either add ClientIDMode="Static"
the the element which will lock the ID, or change your selector to $([id$=LangSelect])
, I prefer using ClientIDMode
.
Upvotes: 0