我正在尝试创建一个复选框菜单,每次选中或取消选中复选框菜单项时,该菜单都会输出一组新的值(用于搜索表(。
我可以让表在第一次检查项目时进行过滤,但之后就不行了。
<input type="checkbox" id="cbox1" value="processes" onchange="searchFunction()">
<label for="cbox1">Processes and Roles </label>
</br>
<input type="checkbox" id="cbox2" value="knowledge" onchange="searchFunction()">
<label for="cbox2">Knowledge and Tools </label>
var table = $('#myTable').DataTable();
var searchObject = {};
function searchFunction(id) {
if (document.getElementById('cbox1').checked) {
searchObject.termOne = "processes";
}
if (document.getElementById('cbox2').checked) {
searchObject.termTwo = "knowledge";
}
table.columns(2).search(searchObject.termOne + '|' + searchObject.termTwo, true, false).draw();
};
为了处理我们未选中的情况,可能更容易始终从空搜索参数开始,然后根据需要添加参数:
function searchFunction(id) {
var searchParams = {}; //start with empty search params each time
var cbox1 = document.getElementById('cbox1');
var cbox2 = document.getElementById('cbox2');
if (cbox1.checked) {
searchParams.termOne = "processes";
}
if (cbox2.checked) {
searchParams.termTwo = "knowledge";
}
table.columns(2).search(searchParams.termOne + '|' + searchParams.termTwo, true, false).draw();
};
添加另一个 if 语句,如下所示,在取消选中所有复选框时返回表中的所有行。
function searchFunction(id) {
var searchParams = {}; //start with empty search params each time
var cbox1 = document.getElementById('cbox1');
var cbox2 = document.getElementById('cbox2');
if (cbox1.checked) {
searchParams.termOne = "processes";
}
if (cbox2.checked) {
searchParams.termTwo = "knowledge";
}
if (cbox1.checked == false && cbox2.checked == false) {
searchParams.termOne = "processes";
searchParams.termTwo = "knowledge";
}
table.columns(2).search(searchParams.termOne + '|' + searchParams.termTwo, true, false).draw();
};