다음은 JavaScript를 사용하여 다중 체크박스 조건에 따라 배열을 필터링하는 코드입니다 -
예시
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Filter an array depending on multiple checkbox conditions</h1> <div class="sample">[22,10,50,30,90,33,80,75,33,99,150,105]</div> <div class="result"></div> <br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should be greater than 50<br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 5<br /> <input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 3<br /> <h3>tick the above checkbox to apply filter to the array above</h3> <script> let resEle = document.querySelector(".result"); let checkEle = document.querySelectorAll(".check"); let arr = [22, 10, 50, 30, 90, 33, 80, 75, 33, 99, 150, 105]; let resArr = arr; function filterArr() { checkEle.forEach((item, index) => { if (item.checked && index == 0) { resArr = resArr.filter((num) => num > 50); resEle.innerHTML = resArr; } else if (item.checked && index == 1) { resArr = resArr.filter((num) => num % 5 == 0); resEle.innerHTML = resArr; } else if (item.checked && index == 2) resArr = resArr.filter((num) => num % 3 == 0); resEle.innerHTML = resArr; }); } </script> </body> </html>
출력
위의 코드는 다음과 같은 출력을 생성합니다 -
일부 확인란을 선택하면 -