简体   繁体   中英

How To Select DropDown List ListItem with Text In Variable Or LIke that Text Jquery I Did All Techniques But Remain Unresolve???

i am tryint to select dropdownlist listitem with variable in text or like that text my my jquery is not even selecting the same text as in listitem my code is below,

<asp:DropDownList ID="DDL_State" runat="server" Width="100px" Height="16px">
                    <asp:ListItem Text="" Value="0">State</asp:ListItem>
                    <asp:ListItem Text="Alabama" Value="1">Alabama AL</asp:ListItem>
                    <asp:ListItem Text="Alaska" Value="2">Alaska AK</asp:ListItem>
                    <asp:ListItem Text="Arizona" Value="3">Arizona AZ</asp:ListItem>
                    <asp:ListItem Text="Arkansas" Value="4">Arkansas AR</asp:ListItem>
 </asp:DropDownList>

var state='Alaska';
$("select[id$=ddlDropDownList]").val('Alaska');
        $("#<%=DDL_State.ClientID %> option[text='Alaska']").attr("selected","selected");
        $("#DDL_State").val(state);
        $("#DDL_State option:contains(" + state + ")").attr('selected', 'selected');
        $('#<%=DDL_State.ClientID%>').val(state);

it is not even giving me any error but its sure that jquery is calling properly

Hopes for your suggestions ?

Thanks

Text is not a valid attribute for an asp:ListItem element in asp.net. You should put it in the value field, if possible like this :

<asp:DropDownList ID="DDL_State" runat="server" Width="100px" Height="16px">
    <asp:ListItem Value="">State</asp:ListItem>
    <asp:ListItem Value="Alabama">Alabama AL</asp:ListItem>
    <asp:ListItem Value="Alaska">Alaska AK</asp:ListItem>
    <asp:ListItem Value="Arizona">Arizona AZ</asp:ListItem>
    <asp:ListItem Value="Arkansas">Arkansas AR</asp:ListItem>
</asp:DropDownList>
<script language="javascript" type="text/javascript">
    var state='Alaska';
    $('#<%=DDL_State.ClientID%>').val(state);
</script>

EDIT :

But if you want to select by text, you can use :

$('#<%=DDL_State.ClientID%>').find("option:contains(" + state + ")")
                             .prop("selected", true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM