简体   繁体   中英

How do I get the jquery script "chosen" to work in asp.net

I have this code:

<script type="text/javascript" src="../Scripts/chosen.min.js" ></script>

[...]

<asp:ListBox class="chosen-select" ID="lbCategory" runat="server" AutoPostBack="true" DataSourceID="SqlDataSourceDropDownListCategory" 
SelectionMode="Multiple" Width="200px" DataTextField="Name" DataValueField="IdCategory"></asp:ListBox>

<script>
    $(".chosen-select").chosen();
</script>

I have the js in the path that I wrote and the script dosen't work, I tried to search, but everthing I found doesn't fix it, could someone help please.

What I see as issues.

  1. There is no chosen.min.js in the files. There is the chosen.jquery.min.js and some others.
  2. The AutoPostBack="true" will not work if you use the chosen plugin because the plugin redesign the original control witch now is hidden. Also you use SelectionMode="Multiple" so if the auto post back work in every click you going to have a post back, this is not the best expirience for web.
  3. You do not include the jQuery library that chosen needs to work.
  4. Prefer CssClass and not class . Both works but for asp.net controls the CssClass is the correct one to avoid bugs.

How to find the errors. Open the browser debug tools by right click on page, on the open menu select Inspect and then open Console and see what errors do you have get and take it from there.

Reference

Chosen documentation
Chosen downloads

Working Example

I create a minimum example and test it and works.

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/js/jQuery/Chosen/chosen.jquery.js " ></script>
<link rel="stylesheet" href="/js/jQuery/Chosen/chosen.css" />               

<asp:ListBox ID="lstCategoryType" runat="server" CssClass="chosen-select"  SelectionMode="Multiple" Width="200px">
    <asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
    <asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
    <asp:ListItem Text="Option 3" Value="3"></asp:ListItem>
    <asp:ListItem Text="Option 4" Value="4"></asp:ListItem>
</asp:ListBox>

<script>
    jQuery(document).ready(function(){
        jQuery(".chosen-select").chosen();    
    });
</script>

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