我尝试创建一个复选框菜单,输出一组新值(用于搜索表格)每次检查或取消选中复选框菜单项。
我可以让表格首先检查一个项目,但之后没有。
<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();
};
答案 0 :(得分:0)
要处理我们未选中的情况,可能更容易始终使用空搜索参数,然后根据需要添加参数:
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();
};
答案 1 :(得分:0)
如果取消选中所有复选框,则按以下方式添加另一个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();
};