功能描述:实现带有checkbox表单的提交以及checkbox全选、反选功能。
var $permission = $('.tab-permission'), $tablePermission = $permission.find('.table-permission'),//表单 $box = $tablePermission.find('input[type=checkbox]'),$checkRev=$('.checkRev'),//反选 $selectAll = $tablePermission.find('.select-all-item');//全选
1、全选功能--点击全选框时
//Checkbox $selectAll.on('change', function () { if (!$(this).prop(checked)) { //不用this.checked做判断,prop有更好的兼容性 $selectAll.prop('checked', false); } else { $box.prop('checked', false); } });
2、全选功能--当有所有checkbox项被选择时等价于点击“全选“,当有未被选择项时,应释放“全选“。
$tablePermission.find('.checkboxes').on('change', function () { $(this).each(function () { if (!$(this).prop(checked)) { $selectAll.prop('checked', false); } }); if ($('input[class=checkboxes]:checked').length == $('input[class=checkboxes]').length) { $selectAll.prop('checked', true); } });
3、反选功能--原来checked状态为true的checkbox状态被修改为false;原来为false的修改为true
$checkRev.on('click', function () { $('.checkboxes').each(function () { if($(this).prop('checked',true)){$(this).prop('checked',false);} }); });
4、表单提交--遍历所有的checkbox的状态,创建一个新的对象obj,对象的属性id和checked分别代表一个checkbox的id和状态;idsTemp用于存储所有obj对象所组成的数组。idsTemp数组转化成JSON字符串传到后台。
//Submit button $permission.find('.submit-permission').on('click', function () { var $this = $(this), ids, idsString = '', idsTemp = []; if ($this.hasClass('loading')) { return false; } $this.addClass('loading'); $tablePermission.find('.checkboxes').each(function () { var obj = {}; obj.id = $(this).data('id'); obj.checked = $(this).prop('checked'); idsTemp.push(obj); }); ids = JSON.stringify(idsTemp); $.ajax({ url: getUncachedUrl($this.data('url')), type: 'POST', data: { act: 'create-navigation-json-file', ids: ids }, success: function (data) { console.log(data); if (data.stats === 's') { toastr.success(data.message); } else { toastr.error(data.message); } $this.removeClass('loading'); }, error: function () { showNotificationError(); $this.removeClass('loading'); } }); return false; });
注意:1、声明一个新的对象并添加属性:var obj={};obj.name='a';obj.age='18';
2、将对象加入数组idsTemp.push(obj);