简体   繁体   English

如何在Jquery中的复选框上发布ID?

[英]How to post id on checkbox in Jquery?

I want to make a simple pagination page. 我想制作一个简单的分页页面。 This is regarding delete function. 这与删除功能有关。 I have a checkbox that user can choose to delete a row. 我有一个复选框,用户可以选择删除行。 May I know how to post/get the id of the row if user click on next link? 如果用户单击下一个链接,我可以知道如何发布/获取行的ID吗? In my case, the id will be duplicate if user click on the checkbox. 就我而言,如果用户单击复选框,则ID将重复。 Below are my codes, 以下是我的代码,

jQuery jQuery的

var cbNew = [],
cbAdd = [];

function addId(checkBox){
    cbAdd = cbAdd.concat(checkBox);
    console.log(cbAdd);
}

$(document).on("click", ".checkBox", function(){
    var cb = [];
    $('.checkBox:checked').each(function(){
        cb.push($(this).val());
    });

    if(cb.length > 0) { 
        addId(cb);
        $('#delete').fadeIn(); 
    } else {
        $('#delete').fadeOut();
    }
});

//Link on Next Page
$(".nextPage").click(getFunct);

function getFunct(e){
    e.preventDefault();
    var url = $(this).attr('href'),
    row = getURLParameter(url, 'startrow'),
    cbNew = cbNew;
    getParam(row,url);
}

function getParam(param1,param2){
    $.ajax({
        type: "POST",
        url: url,
        data: 
        {
            row : param1,
            url : param2,
            cbNew : cbNew
        }
    }).done(function(data){
        $('#result').html(data);
        addId(cbNew);
    });
}

This is the output if I click on multiple checkbox on same page console.log(cbAdd); 如果单击同一页面上的多个复选框,则输出为console.log(cbAdd);

["25", "25", "26", "25", "26", "27"]

If I click one checkbox on page 1 and one checkbox on page 2, it get the id correcltly 如果我单击第1页上的一个复选框和第2页上的一个复选框,则会正确获取ID

["25", "59"]

You are maintaining two arrays, one capture all checked checkbox values ie cb and concatenating these to another array called cbAdd, here you are duplicating values. 您要维护两个数组,其中一个捕获所有选中的复选框值,即cb,并将它们连接到另一个名为cbAdd的数组,这里您正在复制值。

lets use single array cbAdd as below - 让我们如下使用单个数组cbAdd-

$(document).on("change", ".checkBox", function(){
    var value = $(this).val();
    var index = cbAdd.indexOf(value);
    if ($(this).is(":checked")) {
      cbAdd.push(value); //put value
    } else {
       cbAdd.splice(index, 1);//remove value
    }
    if(cbAdd.length > 0) { 
        $('#delete').fadeIn(); 
    } else {
        $('#delete').fadeOut();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM