【问题标题】:Get id of checked check boxes in a list on click of a button单击按钮获取列表中选中复选框的 ID
【发布时间】:2013-09-23 07:08:34
【问题描述】:

我在每一行都有一个复选框。我有一个按钮,可以删除选中复选框的所有行。为此,我必须获取选中复选框的行的 ID。我编写了以下代码。但不工作。请大家帮帮我..

按钮代码:<a class="row-delete" align="left" onclick="deleteItem()"/>

function deleteItem(){
    if (confirm("Are you sure you want to delete?")){               
         $(":checkbox").change(function() {
            var notChecked = [], checked = [];
            $(":checkbox").map(function() {
               this.checked ? checked.push(this.id) : notChecked.push(this.id);
            });
            alert("checked: " + checked);
         });
         deleteAll(checked,0);
    }
}

上面的代码有什么问题?

【问题讨论】:

  • 已选中 = [];并且 this.checked 可能有冲突
  • 不确定该代码有什么问题(除了您对.map 的使用不正确),但您可以获取$(":checkbox:checked").get() 以获取所有复选框
  • $(":checkbox:checked").get().. 我应该在 $(":checkbox").map(function() 的地方使用吗??

标签: javascript jquery html jqgrid scripting


【解决方案1】:

您在 deleteItem 方法中注册了一个不需要的 change 事件处理程序,您只需使用 .each() 遍历复选框并更新所需的数组

此外,最好使用.each() 而不是.map(),因为您不会返回任何值

function deleteItem(){
    if (confirm("Are you sure you want to delete?")){               
        var notChecked = [], checked = [];
        $(":checkbox").each(function() {
            if(this.checked){
                checked.push(this.id);
            } else {
                notChecked.push(this.id);
            }
        });
        alert("checked: " + checked);
        deleteAll(checked,0);
    }
}

【讨论】:

    【解决方案2】:

    deleteItem 中删除onchange function,因为当您在linkclick 时,它会在re-init 更改checkbox elements 时出现re-init

    function deleteItem(){
        if (confirm("Are you sure you want to delete?")){               
             var notChecked = [], checked = [];
             $(":checkbox").each(function() {
                id=this.id;
                this.checked ? checked.push(id) : notChecked.push(id);
             });
             alert("checked: " + checked);
             deleteAll(checked,0);
        }
    }
    

    您可以创建一个array of checked checkboxes 喜欢,

       $(":checkbox:checked").each(function() {
            checked.push(this.id);
       });
    

    并且如果你想在复选框的点击上删除项目然后试试,

    $(":checkbox").on('click',function() {
       if($(this).is(':checked')){
          alert($(this).attr('id'));// this item is ready to delete
       }
    });
    

    【讨论】:

    • 我需要从“全部删除”按钮中删除。我必须将行的 id 传递给 deleteAll 方法..
    • 好吧,那就不要使用我answerlast one方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多