Issue
I have simple function where I have 3 checkboxes and trying to something like if are checkboxes unchecked, button should be disabled and if I check all (not just 1 or 2), button will activate
function sub() {
var a = document.getElementById("ch1");
var b = document.getElementById("ch2");
var c = document.getElementById("ch3");
var btn = document.getElementById("btn")
if (a.checked == true && b.checked == true && c.checked == true){
return btn.disabled = !!this.checked;
}
else {
return btn.disabled;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<input type="checkbox" id="ch1" >
<input type="checkbox" id="ch2" >
<input type="checkbox" id="ch3" >
<button onclick="sub()" id="btn">Submit</button>
</body>
<script>
</script>
</html>
Solution
You need to add an EventListener
to the checkboxes and listen if their state change not add the script to a button itself:
let checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(el =>
el.addEventListener('change', function() {
let checked_checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
if (checked_checkboxes.length === checkboxes.length) {
document.querySelector('#btn').removeAttribute('disabled');
} else {
document.querySelector('#btn').setAttribute('disabled', true);
}
})
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<input type="checkbox" id="ch1" >
<input type="checkbox" id="ch2" >
<input type="checkbox" id="ch3" >
<button onclick="sub()" id="btn" disabled>Submit</button>
</body>
<script>
</script>
</html>
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.