ListBox items remains after replace by empty array in jQuery

試著忘記壹切 提交于 2019-12-11 13:42:44

问题


I have a list box which I want to clear by jQuery without page refresh.

<asp:ListBox ID="lbComplaints" runat="server" 
ClientIDMode="Static" SelectionMode="Multiple" 
placeholder="Select Complaints" Style="width: 280px;" AppendDataBoundItems="True">

in a button click

$('input[type="submit"]').click(function (e) {
        e.preventDefault(); 
    $("#lbComplaints").val([]);    
)};

It does not show any error but the items remain in previous selection.

I tried

 $("#lbComplaints").empty();

but all the data of the Listbox is removed but I do not want to remove options but unselection of previous option in Listbox value so that user can select again. How can I do that?

By the way i used

$('#lbComplaints').select2({
        placeholder: 'select a state',
        //tags: "true",
        //allowClear: true,
        theme: "classic"
    });

回答1:


You can try something like this to get it reset:

 $("#lbComplaints option:selected").removeAttr("selected");



回答2:


Unselect

$("#lbComplaints").find("option").attr("selected", false);

You are using select2.js. Modify your javascript as below

var $listX = $('#lbComplaints').select2({
        placeholder: 'select a state',
        //tags: "true",
        //allowClear: true,
        theme: "classic"
    });

    $('input[type="submit"]').click(function (e) {
            e.preventDefault(); 
           $listX.val(null);
    )};

see the documentation here https://select2.github.io/examples.html#programmatic-control




回答3:


But a similar answer was found in

link

As i am using select2 jQuery cannot clear selected items so using select2 $('#lbComplaints').select2('data', null); this works perfectly



来源:https://stackoverflow.com/questions/35968135/listbox-items-remains-after-replace-by-empty-array-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!