在自举模式中单击上一个和下一个保留复选框选择 [英] Retain checkbox selection on click of previous and next in the bootstrap modal

查看:186
本文介绍了在自举模式中单击上一个和下一个保留复选框选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引导模态,其中包含一个用户表。
我可以从表中选择一个用户,点击保存,显示所选用户的详细信息。
我在模式的表格中每页显示10个用户。
但是,如果我从第1页选择任何用户,然后单击下一步从第2页选择一些用户,然后单击保存,我的第1页的选择不会保留。



我的意思是,当我点击下一个或上一个时,第1页上的复选框被清除。
如何在我的复选框上保留此选择,即使我在任何页面上点击下一页或上一页?



这是代码片段:



  var currentPageNo = 0; //跟踪当前显示的页面//选择userList $('#userList .prev-btn')的后代的按钮。click(function(){userList(currentPageNo-10);}); $('#userList点击(function(){userList(currentPageNo + 10);}); $('#adminList .prev-btn')点击(function(){adminList(currentPageNo-10);}) ; $('#adminList .next-btn')。click(function(){adminList(currentPageNo + 10);}); function userList(pageNo){var resType =userList; createTable(resType,pageNo);} function adminList(pageNo){var resType =adminList; createTable(resType,pageNo);} function createTable(resType,pageNo){//更新全局变量currentPageNo = pageNo; //设置正确的prev按钮的可见性:$('#'+ resType +'.prev-btn')toggle(pageNo> 0); //请求一个以上的记录,以确定此页面之后是否有更多记录:$ .getJSON(https://api.randomuser.me/?results=11&resType=+ resType +& pageIndex =+ pageNo,function(data){var $ table = $('#'+ resType +'table'); $('tr:has(td)',$ table).empty(); //检查是否有一个额外的记录,我们不显示,但是确定有一个下一页$('#'+ resType +'.next-btn')。toggle(data.results.length> 10); // Slice结果,所以第11个记录不包括在内:data.results.slice(0,10).forEach(function(record,i){//添加第二个参数用于编号记录var json = JSON.stringify(record); $ table .append($('< tr>')。append($('< td>')。append($('< input>')。attr('type','checkbox').addClass 'selectRow') 。$('< a>')。attr ).addClass('imgurl').attr('target','_blank').text(record.name.first)),$('< td>')。append(record.dob) ); }); //显示prev和/或按钮})。fail(function(error){console.log(********** AJAX ERROR:+ error);}); } var savedData = []; //对象作为数组,所以要有一个order.function saveData(){var errors = []; //添加选择映射$('input.selectRow:checked')。each(function(count){//获取存储为checkbox的值的JSON var obj = JSON.parse($(this).val ()); //看看这个URL是否已经被收集(这很容易使用Set)if(savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)){errors.push(obj .name.first);} else {//附加它savedData.push(obj);}}); refreshDisplay(); if(errors.length){alert('以下内容已经被选中:\\\
'+ errors.join('\\\
')); }} function refreshDisplay(){$('。container')。html(''); saveData.forEach(function(obj){//重置容器,并附加收集的数据(使用jQuery进行追加)$('。container')。append($('< div>')addClass('parent' .append($('< label>')。addClass('dataLabel')。text('Name:'),obj.name.first +''+ obj.name.last,$('< br& '),// name& pic $('< img>')之间的换行符,addClass('myLink')。attr('src',obj.picture.thumbnail),$('< br> '',$('< label>')。addClass('dataLabel')。text('Date of birth:'),obj.dob,$('< br>'),$('< label> ;')。addClass('dataLabel')。text('Address:'),$('< br>'),obj.location.street,$('< br>'),obj.location.city +''+ obj.location.postcode,$('< br>'),obj.location.state,$('< br> $('< button>')。addClass('removeMe')。text('Delete'),$('< button>')addClass('top-btn' ),$('< button>')。addClass('down-btn')。text('Swap with down'))); })//清除复选框:$('。selectRow')。prop('checked',false); handleEvents();} function logSavedData(){//转换为JSON并记录到控制台。你会把它//发布到一些URL,或保存到localStorage。 console.log(JSON.stringify(savedData,null,2));} function getIndex(elem){return $(elem).parent('。parent')。index();} $(document)单击','.removeMe',function(){//从保存的Data savedData.splice(getIndex(this),1); //重新显示refreshDisplay();}); / *将显示的文章结果列表* / $(document).on('click','.down-btn,function(){var index = getIndex(this); //在内存中交换saveData.splice(index,2,savedData [索引+ 1],savedData [index]); //重新显示refreshDisplay();}); $(document).on('click',.top-btn,function(){var index = getIndex ); //在内存中交换内存savedData.splice(index-1,2,savedData [index],savedData [index-1]); //并重新显示refreshDisplay();}); / *禁用顶部&结果列表中第一个和最后一个文章的下拉按钮* / function handleEvents(){$(。top-btn,.down-btn)。prop(disabled,false).show(); $(。parent:first)。find(。top-btn)。prop(disabled,true).hide(); $(文件).ready(function(){$('#showExtForm -b()()()()()()()()() ;}); function addExtUser(){var extObj = {name:{title:mr,// No ladies? :-) first:$(#name)。val(),//姓氏? },dob:$(#dob)。val(),图片:{thumbnail:$(#myImg)。val()},location:{//也可能要求这个信息? }}; savedData.push(extObj); refreshDisplay(); //将显示一些未定义的东西(位置...)}

  .parent {background-color:#0000FF;颜色:白色; border = 1px solid black;}  

 < link href = https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css =stylesheet/>< script src =https://ajax.googleapis.com/ajax /libs/jquery/2.1.1/jquery.min.js\"></script><script src =https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min。 js>< / script>< button class =btn btn-primary btn-smdata-toggle =modaldata-target =#userListonclick =userList(0)>用户列表< ; / button>< button class =btn btn-primary btn-smonclick =logSavedData()>获取保存的数据< / button>< button class =btn btn-primary btn-smdata- toggle =modaldata-target =#adminListonclick =adminList(0)> User Admin< / button>< button class =btn btn-primary btn-smdata-toggle =modal data-target =#extUser>打开外部窗体< / button> < div class =modal fadeid =userListrole =dialog> < div class =modal-dialog modal-lg> < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>用户列表< / h4> < / DIV> < div class =modal-body> < div class =table-responsive> < table class =table table-bordered table-hoverid =datatable> < TR> <的第i;选择< /第> <的第i;姓名< /第> <的第i; DOB< /第> < / TR> < /表> < / DIV> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary prev-btn>< span class =glyphicon glyphicon-chevron-left>< / span>< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary next-btn>< span class =glyphicon glyphicon-chevron-right>< / span>< / button> < / DIV> < / DIV> < HR /> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary btn-smonclick =saveData()>保存所选的< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary btn-sm close-less-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < br /> < / DIV> < / DIV> < / div>< / div>< div class =modal fadeid =adminListrole =dialog> < div class =modal-dialog modal-lg> < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>管理列表< / h4> < / DIV> < div class =modal-body> < div class =table-responsive> < table class =table table-bordered table-hoverid =datatable> < TR> <的第i;选择< /第> <的第i;姓名< /第> <的第i; DOB< /第> < / TR> < /表> < / DIV> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary prev-btn>< span class =glyphicon glyphicon-chevron-left>< / span>< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary next-btn>< span class =glyphicon glyphicon-chevron-right>< / span>< / button> < / DIV> < / DIV> < HR /> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary btn-smonclick =saveData()>保存所选的< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary btn-sm close-less-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < br /> < / DIV> < / DIV> < / div>< / div>< div class =modal fadeid =extUserrole =dialog> < div class =modal-dialog modal-lg> <! - 外部用户 - > < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>添加外部用户< / h4> < / DIV> < div class =modal-body> < form class =form-horizo​​ntalid =extUserForm> < div class =form-group> < label class =control-label col-sm-3for =name> Name:< / label> < div class =col-sm-8> < input type =textclass =form-controlid =namename =namerequired> < / DIV> < / DIV> < div class =form-group> < label class =control-label col-sm-3for =myImg> Image:< / label> < div class =col-sm-8> < input type =textclass =form-controlid =myImgname =myImgrequired> < / DIV> < / DIV> < div class =form-group> < label class =control-label col-sm-3for =dob> DOB:< / label> < div class =col-sm-8> < input type =dateclass =form-controlid =dobname =dobrequired> < / DIV> < / DIV> < hr /> < div class =form-group> < div class =col-sm-offset-3 col-sm-3> < button class =btn btn-primary btn-sm> Submit< / button> < / DIV> < div class =col-sm-3> < button type =resetclass =btn btn-primary btn-sm> Reset< / button> < / DIV> < div class =col-sm-3> < button type =buttonclass =btn btn-primary btn-sm close-external-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < /形式> < / DIV> < / DIV> < / DIV> < / div>< div class =container>< / div>  

解决方案

如果你想让复选框持续,即使你移动到另一个页面,我建议你实际上保持这些行与复选框,但只是隐藏他们移动



这个想法是,您永远不会删除行,但只有在移动到尚未访问的页面时才添加它们。但是当回到上一页时,您只需将这10行显示出来,并隐藏所有其他页面。这样,您甚至可以拥有更好的用户体验,因为这些页面不需要再从服务器请求。



为了实现这一点,你只需要在 creatTable 函数的前几行中进行一些修改:

  function createTable(resType, pageNo){
//更新全局变量
currentPageNo = pageNo;
//设置正确的prev按钮的可见性:
$('#'+ resType +'.prev-btn')toggle(pageNo> 0);
// ***看看我们是否已经加载了该页面
var $ table = $('#'+ resType +'table');
// ***计算表中已有的行,查看我们是否已经有页面
var lastPageNo = $('tr:has(td)',$ table).length - 1 ;
if(currentPageNo< lastPageNo){
// ***我们有页面:隐藏所有行,除了那个页面
$('tr:has(td)', $ table).hide()。slice(currentPageNo,currentPageNo + 10).show();
return;
}
//否则请求。
//请求一个以上的记录,以确定此页面之后是否有更多记录:
$ .getJSON(https://api.randomuser.me/?results=11&resType= + resType +& pageIndex =+ pageNo,function(data){
// ***不清除表,但是隐藏所有行,所以当回传$ b $时可以重新使用b $('tr:have(td)',$ table).hide();
//检查是否有一个额外的记录,我们不显示,
//但是确定有一个下一页
$('#'+ resType +'.next-btn')。toggle(data.results.length> 10);
// ... etc ... etc

以下是全部代码段:



< pre class =snippet-code-js lang-js prettyprint-override> var currentPageNo = 0; //跟踪当前显示的页面//选择按钮这是userList $('#userList .prev-btn')的后代。click(function(){userList(currentPageNo-10);}); $('#userList .next-btn')。 {userList(currentPageNo + 10);}); $('#adminList .prev-btn')点击(function(){adminList(currentPageNo-10);}); $('#adminList .next-btn' .click(function(){adminList(currentPageNo + 10);}); function userList(pageNo){var resType =userList; createTable(resType,pageNo);} function adminList(pageNo){var resType =adminList; createTable(resType,pageNo);} function createTable(resType,pageNo){//更新全局变量currentPageNo = pageNo; //设置正确的prev按钮的可见性:$('#'+ resType +'.prev-btn')toggle(pageNo> 0); // ***看看我们是否已经加载了该页面var $ table = $('#'+ resType +'table'); // ***计算表中已有的行,看看是否已经有页面var lastPageNo = $('tr:has(td)',$ table).length - 1; if(currentPageNo< lastPageNo){// ***我们有页面:隐藏所有行,除了那个页面$('tr:has(td)',$ table).hide()。slice(currentPageNo, currentPageNo + 10).show();返回; } //否则请求。 //请求一个以上的记录,以确定此页面之后是否有更多记录:$ .getJSON(https://api.randomuser.me/?results=11&resType=+ resType +& pageIndex =+ pageNo,function(data){// ***不清除表,但隐藏所有行,所以当回调$('tr:has(td)',$ table)时可以重复使用它们。 hide(); //检查是否有一个额外的记录,我们不显示,//但是确定有一个下一页$('#'+ resType +'.next-btn')。toggle(data.results。长度> 10); //切片结果,所以不包括第11个记录:data.results.slice(0,10).forEach(function(record,i){//添加第二个参数用于编号记录var json = JSON .stringify(record); $ table.append($('< tr>')。append($('< td>')。append($('< input> ,'checkbox') 。addClass('selectRow').val(json),(i + 1 + pageNo)//显示行号),$('< td>')。append($('< a> ('href',record.picture.thumbnail).addClass('imgurl').attr('target','_blank').text(record.name.first)),$('< td>')。 append(record.dob))); }); })。fail(function(error){console.log(********** AJAX ERROR:+ error);}); } var savedData = []; //对象作为数组,所以要有一个order.function saveData(){var errors = []; //添加选择映射$('input.selectRow:checked')。each(function(count){//获取存储为checkbox的值的JSON var obj = JSON.parse($(this).val ()); //看看这个URL是否已经被收集(这很容易使用Set)if(savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)){errors.push(obj .name.first);} else {//附加它savedData.push(obj);}}); refreshDisplay(); if(errors.length){alert('以下内容已经被选中:\\\
'+ errors.join('\\\
')); }} function refreshDisplay(){$('。container')。html(''); saveData.forEach(function(obj){//重置容器,并附加收集的数据(使用jQuery进行追加)$('。container')。append($('< div>')addClass('parent' .append($('< label>')。addClass('dataLabel')。text('Name:'),obj.name.first +''+ obj.name.last,$('< br& '),// name& pic $('< img>')之间的换行符,addClass('myLink')。attr('src',obj.picture.thumbnail),$('< br> '',$('< label>')。addClass('dataLabel')。text('Date of birth:'),obj.dob,$('< br>'),$('< label> ;')。addClass('dataLabel')。text('Address:'),$('< br>'),obj.location.street,$('< br>'),obj.location.city +''+ obj.location.postcode,$('< br>'),obj.location.state,$('< br> $('< button>')。addClass('removeMe')。text('Delete'),$('< button>')addClass('top-btn' ),$('< button>')。addClass('down-btn')。text('Swap with down'))); })//清除复选框:$('。selectRow')。prop('checked',false); handleEvents();} function logSavedData(){//转换为JSON并记录到控制台。你会把它//发布到一些URL,或保存到localStorage。 console.log(JSON.stringify(savedData,null,2));} function getIndex(elem){return $(elem).parent('。parent')。index();} $(document)单击','.removeMe',function(){//从保存的Data savedData.splice(getIndex(this),1); //重新显示refreshDisplay();}); / *将显示的文章结果列表* / $(document).on('click','.down-btn,function(){var index = getIndex(this); //在内存中交换saveData.splice(index,2,savedData [索引+ 1],savedData [index]); //重新显示refreshDisplay();}); $(document).on('click',.top-btn,function(){var index = getIndex ); //在内存中交换内存savedData.splice(index-1,2,savedData [index],savedData [index-1]); //并重新显示refreshDisplay();}); / *禁用顶部&结果列表中第一个和最后一个文章的下拉按钮* / function handleEvents(){$(。top-btn,.down-btn)。prop(disabled,false).show(); $(。parent:first)。find(。top-btn)。prop(disabled,true).hide(); $(文件).ready(function(){$('#showExtForm -b()()()()()()()()() ;}); function addExtUser(){var extObj = {name:{title:mr,// No ladies? :-) first:$(#name)。val(),//姓氏? },dob:$(#dob)。val(),图片:{thumbnail:$(#myImg)。val()},location:{//也可能要求这个信息? }}; savedData.push(extObj); refreshDisplay(); //将显示一些未定义的东西(位置...)}

 < link href =https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css =stylesheet/>< script src =https:// ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><script src =https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7 /js/bootstrap.min.js\"></script><button class =btn btn-primary btn-smdata-toggle =modaldata-target =#userListonclick =userList 0)>用户列表< / button>< button class =btn btn-primary btn-smonclick =logSavedData()>获取保存的数据< / button>< button class =btn btn- primary btn-smdata-toggle =modaldata-target =#adminListonclick =adminList(0)> User Admin< / button>< button class =btn btn-primary btn-sm data-toggle =modaldata-target =#extUser>打开外部窗体< / button> < div class =modal fadeid =userListrole =dialog> < div class =modal-dialog modal-lg> < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>用户列表< / h4> < / DIV> < div class =modal-body> < div class =table-responsive> < table class =table table-bordered table-hoverid =datatable> < TR> <的第i;选择< /第> <的第i;姓名< /第> <的第i; DOB< /第> < / TR> < /表> < / DIV> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary prev-btn>< span class =glyphicon glyphicon-chevron-left>< / span>< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary next-btn>< span class =glyphicon glyphicon-chevron-right>< / span>< / button> < / DIV> < / DIV> < HR /> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary btn-smonclick =saveData()>保存所选的< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary btn-sm close-less-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < br /> < / DIV> < / DIV> < / div>< / div>< div class =modal fadeid =adminListrole =dialog> < div class =modal-dialog modal-lg> < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>管理列表< / h4> < / DIV> < div class =modal-body> < div class =table-responsive> < table class =table table-bordered table-hoverid =datatable> < TR> <的第i;选择< /第> <的第i;姓名< /第> <的第i; DOB< /第> < / TR> < /表> < / DIV> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary prev-btn>< span class =glyphicon glyphicon-chevron-left>< / span>< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary next-btn>< span class =glyphicon glyphicon-chevron-right>< / span>< / button> < / DIV> < / DIV> < HR /> < div class =row> < div class =col-sm-offset-3 col-sm-4> < button type =buttonclass =btn btn-primary btn-smonclick =saveData()>保存所选的< / button> < / DIV> < div class =col-sm-4> < button type =buttonclass =btn btn-primary btn-sm close-less-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < br /> < / DIV> < / DIV> < / div>< / div>< div class =modal fadeid =extUserrole =dialog> < div class =modal-dialog modal-lg> <! - 外部用户 - > < div class =modal-content> < div class =modal-header> < button type =buttonclass =closedata-dismiss =modal>& times;< / button> < h4 class =modal-title>添加外部用户< / h4> < / DIV> < div class =modal-body> < form class =form-horizo​​ntalid =extUserForm> < div class =form-group> < label class =control-label col-sm-3for =name> Name:< / label> < div class =col-sm-8> < input type =textclass =form-controlid =namename =namerequired> < / DIV> < / DIV> < div class =form-group> < label class =control-label col-sm-3for =myImg> Image:< / label> < div class =col-sm-8> < input type =textclass =form-controlid =myImgname =myImgrequired> < / DIV> < / DIV> < div class =form-group> < label class =control-label col-sm-3for =dob> DOB:< / label> < div class =col-sm-8> < input type =dateclass =form-controlid =dobname =dobrequired> < / DIV> < / DIV> < hr /> < div class =form-group> < div class =col-sm-offset-3 col-sm-3> < button class =btn btn-primary btn-sm> Submit< / button> < / DIV> < div class =col-sm-3> < button type =resetclass =btn btn-primary btn-sm> Reset< / button> < / DIV> < div class =col-sm-3> < button type =buttonclass =btn btn-primary btn-sm close-external-modaldata-dismiss =modal>关闭< / button> < / DIV> < / DIV> < /形式> < / DIV> < / DIV> < / DIV> < / div>< div class =container>< / div>  


I've a bootstrap modal which contains a table of users. I can select a user from the table and on clicking 'save', the details of seleced user is displayed. I'm displaying 10 users per page in the table of the modal. However, if I select any user from page 1 and then click next to select some users from page 2 and click on 'save', my selection from page 1 is not retained.

I mean the checkbox is cleared on page 1, whenever I click on next or previous. How do I retain this selection on my checkbox, even if I click on next or previous at any page?

Here's the snippet:

var currentPageNo = 0; // Keep track of currently displayed page


// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){ 
    userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){ 
    userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){ 
    adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){ 
    adminList(currentPageNo+10);
});

function userList(pageNo) {
    var resType="userList";
    createTable(resType,pageNo);
}

function adminList(pageNo) {
    var resType="adminList";
    createTable(resType,pageNo);
}

function createTable(resType, pageNo) {
    // Update global variable
    currentPageNo = pageNo; 
    // Set visibility of the correct "prev" button:
    $('#' + resType + ' .prev-btn').toggle(pageNo > 0);
    // Ask one record more than needed, to determine if there are more records after this page:
    $.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
        var $table = $('#' + resType + ' table');
        $('tr:has(td)', $table).empty();
        // Check if there's an extra record which we do not display, 
        // but determines that there is a next page
        $('#' + resType + ' .next-btn').toggle(data.results.length > 10);
        // Slice results, so 11th record is not included:
        data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
            var json = JSON.stringify(record);
            $table.append(
                $('<tr>').append(
                    $('<td>').append(
                        $('<input>').attr('type', 'checkbox')
                                    .addClass('selectRow')
                                    .val(json),
                        (i+1+pageNo) // display row number
                    ),
                    $('<td>').append(
                        $('<a>').attr('href', record.picture.thumbnail)
                                .addClass('imgurl')
                                .attr('target', '_blank')
                                .text(record.name.first)
                    ),
                    $('<td>').append(record.dob)
                )
            );
        });
        // Show the prev and/or buttons
        
        
    }).fail(function(error) {
        console.log("**********AJAX ERROR: " + error);
    });            
}

var savedData = []; // The objects as array, so to have an order.

function saveData(){
    var errors = [];
    // Add selected to map
    $('input.selectRow:checked').each(function(count) {
        // Get the JSON that is stored as value for the checkbox
        var obj = JSON.parse($(this).val());
        // See if this URL was already collected (that's easy with Set)
        if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
            errors.push(obj.name.first);
        } else {
            // Append it
            savedData.push(obj);
        }
    });
    refreshDisplay();
    if (errors.length) {
        alert('The following were already selected:\n' + errors.join('\n'));
    }
}

function refreshDisplay() {
    $('.container').html('');
    savedData.forEach(function (obj) {
        // Reset container, and append collected data (use jQuery for appending)
        $('.container').append(
            $('<div>').addClass('parent').append(
                $('<label>').addClass('dataLabel').text('Name: '),
                obj.name.first + ' ' + obj.name.last,
                $('<br>'), // line-break between name & pic
                $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
                $('<label>').addClass('dataLabel').text('Date of birth: '),
                obj.dob, $('<br>'),
                $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
                obj.location.street, $('<br>'),
                obj.location.city + ' ' + obj.location.postcode, $('<br>'),
                obj.location.state, $('<br>'),
                $('<button>').addClass('removeMe').text('Delete'),
                $('<button>').addClass('top-btn').text('Swap with top'),
                $('<button>').addClass('down-btn').text('Swap with down')
            )	
        );
    })
    // Clear checkboxes:
    $('.selectRow').prop('checked', false);
    handleEvents();
}

function logSavedData(){
    // Convert to JSON and log to console. You would instead post it
    // to some URL, or save it to localStorage.
    console.log(JSON.stringify(savedData, null, 2));
}

function getIndex(elem) {
    return $(elem).parent('.parent').index();
}

$(document).on('click', '.removeMe', function() {
    // Delete this from the saved Data
    savedData.splice(getIndex(this), 1);
    // And redisplay
    refreshDisplay();
});

/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index, 2, savedData[index+1], savedData[index]);
    // And redisplay
    refreshDisplay();
});

$(document).on('click', ".top-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
    // And redisplay
    refreshDisplay();
});
    
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}

$(document).ready(function(){
    $('#showExtForm-btn').click(function(){
        $('#extUser').toggle();
    });
    $("#extUserForm").submit(function(e){
        addExtUser();
        return false;
   });
});

function addExtUser() {
    var extObj = {
        name: {
            title: "mr", // No ladies? :-)
            first: $("#name").val(),
            // Last name ?
        },
        dob: $("#dob").val(),
        picture: {
            thumbnail: $("#myImg").val()
        },
        location: { // maybe also ask for this info?
        }
    };
    savedData.push(extObj);
    refreshDisplay(); // Will show some undefined stuff (location...)
}

.parent {
	background-color: #0000FF;
	color: white;
	border: 1px solid black;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>

  <div class="modal fade" id="userList" role="dialog">
    <div class="modal-dialog modal-lg">
    
      
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">User List</h4>
        </div>
        <div class="modal-body">
          <div class="table-responsive">
              <table class="table table-bordered table-hover" id="datatable">
                <tr>
                    <th>Select</th>
                    <th>Name</th>
                    <th>DOB</th>
                </tr>
            </table>
          </div>
          <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
            </div>

            <div class="col-sm-4">
                <button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
            </div>
        </div>
            <hr/>
        <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
            </div>
            <div class="col-sm-4">
                <button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
            </div>
        </div>
        <br />
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="adminList" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Admin List</h4>
        </div>
        <div class="modal-body">
          <div class="table-responsive">
              <table class="table table-bordered table-hover" id="datatable">
                <tr>
                    <th>Select</th>
                    <th>Name</th>
                    <th>DOB</th>
                </tr>
            </table>
          </div>
          <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
            </div>

            <div class="col-sm-4">
                <button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
            </div>
        </div>
            <hr/>
        <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
            </div>
            <div class="col-sm-4">
                <button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
            </div>
        </div>
        <br />
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="extUser" role="dialog">
    <div class="modal-dialog modal-lg">
    
      <!-- External User-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add External User</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal" id="extUserForm">
            <div class="form-group">
              <label class="control-label col-sm-3" for="name">Name:</label>
              <div class="col-sm-8">
                <input type="text" class="form-control" id="name" name="name" required>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-sm-3" for="myImg">Image:</label>
              <div class="col-sm-8">
                <input type="text" class="form-control" id="myImg" name="myImg" required>
              </div>
            </div>
                                            
            <div class="form-group">
              <label class="control-label col-sm-3" for="dob">DOB:</label>
              <div class="col-sm-8">
                <input type="date" class="form-control" id="dob" name="dob" required>
              </div>
            </div>
            <hr />
            <div class="form-group">        
              <div class="col-sm-offset-3 col-sm-3">
                <button class="btn btn-primary btn-sm">Submit</button>
              </div>
              <div class="col-sm-3">
                <button type="reset" class="btn btn-primary btn-sm">Reset</button>
              </div>
              <div class="col-sm-3">
                <button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
              </div>
            </div>
          </form>
        </div> 
      </div>
    </div>
  </div>

<div class="container"></div>

解决方案

If you want the checkboxes to persist even when you move to another page, I would suggest that you actually keep those rows with checkboxes, but just hide them when moving to the next page.

The idea is that you never remove rows, but only add them when moving to a page you had not yet visited. But when going back to previous pages, you just make those 10 rows visible, and hide all others. That way you will even have a better user-experience, since those pages do not have to be requested from the server any more.

To achieve this, you just have to make a few changes in the first few lines of the creatTable function:

function createTable(resType, pageNo) {
    // Update global variable
    currentPageNo = pageNo; 
    // Set visibility of the correct "prev" button:
    $('#' + resType + ' .prev-btn').toggle(pageNo > 0);
    // *** See if we have that page already loaded
    var $table = $('#' + resType + ' table');
    // *** Count the rows already in the table, to see if we already have the page
    var lastPageNo = $('tr:has(td)', $table).length - 1;
    if (currentPageNo < lastPageNo) {
        // *** We have the page: hide all rows, except those of that page
        $('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
        return;
    }
    // Otherwise make the request.
    // Ask one record more than needed, to determine if there are more records after this page:
    $.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
        //*** don't clear the table, but hide all rows, so they can be reused when paging back
        $('tr:has(td)', $table).hide();
        // Check if there's an extra record which we do not display, 
        // but determines that there is a next page
        $('#' + resType + ' .next-btn').toggle(data.results.length > 10);
        // ...etc ... etc

Here is the whole snippet:

var currentPageNo = 0; // Keep track of currently displayed page

// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){ 
    userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){ 
    userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){ 
    adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){ 
    adminList(currentPageNo+10);
});

function userList(pageNo) {
    var resType="userList";
    createTable(resType,pageNo);
}

function adminList(pageNo) {
    var resType="adminList";
    createTable(resType,pageNo);
}

function createTable(resType, pageNo) {
    // Update global variable
    currentPageNo = pageNo; 
    // Set visibility of the correct "prev" button:
    $('#' + resType + ' .prev-btn').toggle(pageNo > 0);
    // *** See if we have that page already loaded
    var $table = $('#' + resType + ' table');
    // *** Count the rows already in the table, to see if we already have the page
    var lastPageNo = $('tr:has(td)', $table).length - 1;
    if (currentPageNo < lastPageNo) {
        // *** We have the page: hide all rows, except those of that page
        $('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
        return;
    }
    // Otherwise make the request.
    // Ask one record more than needed, to determine if there are more records after this page:
    $.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
        //*** don't clear the table, but hide all rows, so they can be reused when paging back
        $('tr:has(td)', $table).hide();
        // Check if there's an extra record which we do not display, 
        // but determines that there is a next page
        $('#' + resType + ' .next-btn').toggle(data.results.length > 10);
        // Slice results, so 11th record is not included:
        data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
            var json = JSON.stringify(record);
            $table.append(
                $('<tr>').append(
                    $('<td>').append(
                        $('<input>').attr('type', 'checkbox')
                                    .addClass('selectRow')
                                    .val(json),
                        (i+1+pageNo) // display row number
                    ),
                    $('<td>').append(
                        $('<a>').attr('href', record.picture.thumbnail)
                                .addClass('imgurl')
                                .attr('target', '_blank')
                                .text(record.name.first)
                    ),
                    $('<td>').append(record.dob)
                )
            );
        });
    }).fail(function(error) {
        console.log("**********AJAX ERROR: " + error);
    });            
}

var savedData = []; // The objects as array, so to have an order.

function saveData(){
    var errors = [];
    // Add selected to map
    $('input.selectRow:checked').each(function(count) {
        // Get the JSON that is stored as value for the checkbox
        var obj = JSON.parse($(this).val());
        // See if this URL was already collected (that's easy with Set)
        if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
            errors.push(obj.name.first);
        } else {
            // Append it
            savedData.push(obj);
        }
    });
    refreshDisplay();
    if (errors.length) {
        alert('The following were already selected:\n' + errors.join('\n'));
    }
}

function refreshDisplay() {
    $('.container').html('');
    savedData.forEach(function (obj) {
        // Reset container, and append collected data (use jQuery for appending)
        $('.container').append(
            $('<div>').addClass('parent').append(
                $('<label>').addClass('dataLabel').text('Name: '),
                obj.name.first + ' ' + obj.name.last,
                $('<br>'), // line-break between name & pic
                $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
                $('<label>').addClass('dataLabel').text('Date of birth: '),
                obj.dob, $('<br>'),
                $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
                obj.location.street, $('<br>'),
                obj.location.city + ' ' + obj.location.postcode, $('<br>'),
                obj.location.state, $('<br>'),
                $('<button>').addClass('removeMe').text('Delete'),
                $('<button>').addClass('top-btn').text('Swap with top'),
                $('<button>').addClass('down-btn').text('Swap with down')
            )	
        );
    })
    // Clear checkboxes:
    $('.selectRow').prop('checked', false);
    handleEvents();
}

function logSavedData(){
    // Convert to JSON and log to console. You would instead post it
    // to some URL, or save it to localStorage.
    console.log(JSON.stringify(savedData, null, 2));
}

function getIndex(elem) {
    return $(elem).parent('.parent').index();
}

$(document).on('click', '.removeMe', function() {
    // Delete this from the saved Data
    savedData.splice(getIndex(this), 1);
    // And redisplay
    refreshDisplay();
});

/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index, 2, savedData[index+1], savedData[index]);
    // And redisplay
    refreshDisplay();
});

$(document).on('click', ".top-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
    // And redisplay
    refreshDisplay();
});
    
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}

$(document).ready(function(){
    $('#showExtForm-btn').click(function(){
        $('#extUser').toggle();
    });
    $("#extUserForm").submit(function(e){
        addExtUser();
        return false;
   });
});

function addExtUser() {
    var extObj = {
        name: {
            title: "mr", // No ladies? :-)
            first: $("#name").val(),
            // Last name ?
        },
        dob: $("#dob").val(),
        picture: {
            thumbnail: $("#myImg").val()
        },
        location: { // maybe also ask for this info?
        }
    };
    savedData.push(extObj);
    refreshDisplay(); // Will show some undefined stuff (location...)
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>

  <div class="modal fade" id="userList" role="dialog">
    <div class="modal-dialog modal-lg">
    
      
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">User List</h4>
        </div>
        <div class="modal-body">
          <div class="table-responsive">
              <table class="table table-bordered table-hover" id="datatable">
                <tr>
                    <th>Select</th>
                    <th>Name</th>
                    <th>DOB</th>
                </tr>
            </table>
          </div>
          <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
            </div>

            <div class="col-sm-4">
                <button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
            </div>
        </div>
            <hr/>
        <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
            </div>
            <div class="col-sm-4">
                <button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
            </div>
        </div>
        <br />
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="adminList" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Admin List</h4>
        </div>
        <div class="modal-body">
          <div class="table-responsive">
              <table class="table table-bordered table-hover" id="datatable">
                <tr>
                    <th>Select</th>
                    <th>Name</th>
                    <th>DOB</th>
                </tr>
            </table>
          </div>
          <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
            </div>

            <div class="col-sm-4">
                <button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
            </div>
        </div>
            <hr/>
        <div class="row">
            <div class="col-sm-offset-3 col-sm-4">
                <button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
            </div>
            <div class="col-sm-4">
                <button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
            </div>
        </div>
        <br />
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="extUser" role="dialog">
    <div class="modal-dialog modal-lg">
    
      <!-- External User-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add External User</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal" id="extUserForm">
            <div class="form-group">
              <label class="control-label col-sm-3" for="name">Name:</label>
              <div class="col-sm-8">
                <input type="text" class="form-control" id="name" name="name" required>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-sm-3" for="myImg">Image:</label>
              <div class="col-sm-8">
                <input type="text" class="form-control" id="myImg" name="myImg" required>
              </div>
            </div>
                                            
            <div class="form-group">
              <label class="control-label col-sm-3" for="dob">DOB:</label>
              <div class="col-sm-8">
                <input type="date" class="form-control" id="dob" name="dob" required>
              </div>
            </div>
            <hr />
            <div class="form-group">        
              <div class="col-sm-offset-3 col-sm-3">
                <button class="btn btn-primary btn-sm">Submit</button>
              </div>
              <div class="col-sm-3">
                <button type="reset" class="btn btn-primary btn-sm">Reset</button>
              </div>
              <div class="col-sm-3">
                <button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
              </div>
            </div>
          </form>
        </div> 
      </div>
    </div>
  </div>

<div class="container"></div>

这篇关于在自举模式中单击上一个和下一个保留复选框选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆