2017-04-10 30 views
0

Iam当前使用select2 jquery插件从ajax调用动态填充的列表中选择数据。我需要实现选择所有功能,以便用户可以通过使用全选按钮一次选择所有选项。我试图在jsfidde中实现这个例子。如何实现选择所有功能与selectj jQuery插件配置了Ajax搜索。

Click here to see the jsfiddle

但对于选择体积较大的物品的数量的清单说500 items.It使得浏览器挂起了一会儿。请提出一个更好的方法来实现这个没有任何性能问题。

$.fn.select2.amd.require([ 
'select2/utils', 
'select2/dropdown', 
'select2/dropdown/attachBody' 
], function (Utils, Dropdown, AttachBody) { 
function SelectAll() { } 

SelectAll.prototype.render = function (decorated) { 
var $rendered = decorated.call(this); 
var self = this; 

var $selectAll = $(
    '<button type="button">Select All</button>' 
); 

$rendered.find('.select2-dropdown').prepend($selectAll); 

$selectAll.on('click', function (e) { 
    var $results = $rendered.find('.select2-results__option[aria-selected=false]'); 

    // Get all results that aren't selected 
    $results.each(function() { 
    var $result = $(this); 

    // Get the data object for it 
    var data = $result.data('data'); 

    // Trigger the select event 
    self.trigger('select', { 
     data: data 
    }); 
    }); 

    self.trigger('close'); 
}); 

return $rendered; 

};

$("select").select2({ 
placeholder: "Select Option(s)...", 
dropdownAdapter: Utils.Decorate(
    Utils.Decorate(
    Dropdown, 
    AttachBody 
), 
    SelectAll 
), 
    }); 
}); 

回答

0

这是 JQuery Select2 - How to select all options

重复的问题,其中对于多个给定的解决方案使用复选框选择。

如果它获得的负载比你应该添加额外的隐藏的领域来获得逗号分隔值。

请尝试下面的代码。 HTML:

<select multiple id="e1" style="width:300px"> 
    <option value="AL">Alabama</option> 
    <option value="Am">Amalapuram</option> 
    <option value="An">Anakapalli</option> 
    <option value="Ak">Akkayapalem</option> 
    <option value="WY">Wyoming</option> 
</select> 
<br> 
<input type="checkbox" id="checkbox" >Select All 
<br> 
<input type="text" id="valueall" value="" name="valueall"> 

JQuery的:

$("#e1").select2(); 
$("#checkbox").click(function(){ 
    if($("#checkbox").is(':checked')){ 
     $("#e1 > option").prop("selected","selected"); 
     <!-- $("#e1").trigger("change"); --> 
     $("#e1").select2('destroy'); 
     $("#e1").hide(); 
     $("#valueall").val($("#e1").val()) 
    }else{ 
     $("#e1 > option").removeAttr("selected"); 
     <!-- $("#e1").trigger("change"); --> 
     $("#e1").select2(); 
     $("#e1").show(); 
     $("#valueall").val($("#e1").val()) 
    } 
}); 

您可以设置输入字段类型= “隐藏”。

+0

是的,但他说它的工作正常,但这使浏览器挂起,当我们选择更多的书房500项。 – rish

+0

@Parth不,我需要确保浏览器不会选择大量的元素,并选择全部 – albert

+0

@albert,因为您还可以将一个复选框选中所有选项,然后选择禁用并在隐藏中获取所有值用逗号分隔的字段。 – Parth