从过滤的复选框值

时间:2015-12-15 01:56:49

标签: jquery arrays checkbox

我有一个场景,其中一长串复选框选项过滤进出PHP / ajax查询。因此,当用户检查一个或多个复选框时,需要创建用户已检查的框的列表。

使用jQuery和.map(),我可以创建检查复选框的初始列表数组。很容易。

var selected_checkboxes;

$( document ).on( 'click', '.checkbox_select', function() {
    var checkbox_selector = $( '.checkbox_select:checked' );

    selected_checkboxes = checkbox_selector.map( function(i, n) {
        return this.value;
    }).get();

    console.log(selected_checkboxes);
});

所以在这里,我们说我有一组10个复选框(复选框1 - 10),我检查前3个。

控制台输出 ["Checkbox 1", "Checkbox 2", "Checkbox 3"]

过滤复选框视图时会出现问题。假设过滤除Checkbox 3,5和6以外的所有复选框。仍然选中复选框3。现在,如果我们检查" Checkbox 5",我们的新列表数组将如下:["Checkbox 3", "Checkbox 5"]

我知道为什么会这样做,但所需的结果是建立在运行过滤器之前先检查过的内容,它应该看起来像["Checkbox 1", "Checkbox 2", "Checkbox 3", "Checkbox 5"]。几乎就像你只是添加到那个初始数组值。

过滤后的复选框无法隐藏/隐藏,因为它是一个基于ajax的查询。

有没有人有任何想法如何让数组像这样工作?任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:1)

你可以做到

var selected_checkboxes = [];
   $("input:[type = 'checkbox']").click(function(event) {
    if ($(this).attr("checked")) {
        selected_checkboxes.push($(this));
    }else{
        var index = selected_checkboxes.indexOf($(this));
        if (index != -1) {
            selected_checkboxes = selected_checkboxes.slice(index, 1);
        }
    }
});
for(var i = 0; i< selected_checkboxes.length;i++){
    console.log(selected_checkboxes[i].val());
}

请尝试!

答案 1 :(得分:0)

此处chekedid是您的输入类型复选框类名称

function selectedMychecbox() {
    checkedid = Array();
    $('.checkedid:checked').each(function () {
        checkedid.push($(this).val());
    });


}
相关问题