Checkbox Check Event Listener
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Single checkbox
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
<input type="checkbox" name="checkbox" />
Event listener for change in checkboxes checked by ulterior means
Associate checkbox to a label like so:
<input
id="chx1"type="checkbox">
<label
for="chx1">STYLE LABEL LIKE A BUTTON</label>
Checkbox #id syncs with label [for]. Once associated when one is clicked -- they both behave as if they were clicked. In the demo a form is wrapped around everything. By introducing a form as the common parent we can register the form to events (click is common, but forms, inputs, etc. have special events). We assign the change event to the form and now the checkboxes can react when each change without being bound to an event listener. Details commented in demo.
// Reference the formconst form = document.forms.Health;// Register the form to change eventform.onchange = testSync;
// Pass Event Object (e)function testSync(e) { // Reference the checked checkbox const checked = e.target; // Get it's #id let ID = e.target.id; // Get the button/label associated with checkbox let button = document.querySelector(`[for=${ID}]`); // if the checkbox is checked... if (checked.checked) { // Set the button/label text to checkbox ID button.textContent = ID; } else { // Otherwise set text to the button/label .class button.textContent = button.className; } return false;}
label { width: 50px; border: 1px solid #cacaca; border-radius: 3px; font-size: 12px; font-family: arial, helvetica, sans-serif; padding: 10px 10px 10px 10px; text-align: center; display: inline-block; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); font-weight: bold; color: #000; background-color: #E6E6E6; background-image: linear-gradient(to bottom, #E6E6E6, #CCC);}
label:hover { border: 1px solid #b3b3b3; background-color: #cdcdcd; background-image: linear-gradient(to bottom, #cdcdcd, #b3b3b3); cursor: pointer;}
<form id='Health'>
<input id="Nutrition" name='health' type="checkbox" value='H1'> Health 1<br> <input id="Activity" name='health' type="checkbox" value='H2'> Health 2<br> <input id="Medical" name='health' type="checkbox" value='H3'> Health 3<br>
<label class='Health1' for="Nutrition">Health1</label><br> <label class='Health2' for="Activity">Health2</label><br> <label class='Health3' for="Medical">Health3</label><br>
</form>
Add Event Listener to checkboxes when selected all at once
Code working with both manually select and click on the "select all"
let checkboxes = $("input[type='checkbox']");
let enabledSettings = [];
// function to show selected checkboxes
function checkbox_fun() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
}
$('.resultObjectsNew').on('click', 'span.selectAllNewObj', function(){
var checked = $(this).parent().next().find('input').prop('checked');
$(this).parent().next().find('input').prop('checked', !checked);
checkbox_fun(); // function call
});
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
checkbox_fun(); // function call
});
Copy above code to below JSFiddle and successfully run code:
https://jsfiddle.net/f3n9vxzk/3/
Checkbox event listener not firing
You are not adding an event, you are calling it instead.
so change
document.querySelector('#op_checkbox_0').addEventListener('change', toggleOpacity(0,'op_checkbox_0'));
To
document.querySelector('#op_checkbox_0').addEventListener('change', ()=> toggleOpacity(0,'op_checkbox_0'));
document.addEventListener("DOMContentLoaded", function (event) { document.querySelector('#op_checkbox_0').addEventListener('change', ()=> toggleOpacity(0,'op_checkbox_0')); document.querySelector('#op_checkbox_1').addEventListener('change', ()=> toggleOpacity(1,'op_checkbox_1')); document.querySelector('#op_checkbox_2').addEventListener('change', ()=> toggleOpacity(2,'op_checkbox_2')); document.querySelector('#op_checkbox_3').addEventListener('change', ()=> toggleOpacity(3,'op_checkbox_3')); document.querySelector('#op_checkbox_4').addEventListener('change', ()=> toggleOpacity(4,'op_checkbox_4')); document.querySelector('#op_checkbox_5').addEventListener('change', ()=> toggleOpacity(5,'op_checkbox_5'));});
function toggleOpacity(value, el_id){ console.log(el_id + "changed")}
<input type="checkbox" id="op_checkbox_0">Aerial<br><input type="checkbox" id="op_checkbox_1">Aerial (Labels)<br><input type="checkbox" id="op_checkbox_2">Road<br><input type="checkbox" id="op_checkbox_3">Road On Demand<br><input type="checkbox" id="op_checkbox_4">OSM Layer<br><input type="checkbox" id="op_checkbox_5">WMS Layer<br>
addEventListener to multiple checkboxes
Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']");
to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections
object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections
.
This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.
Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.
var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");
for (var i = 0; i < checkboxElems.length; i++) {
checkboxElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
name: e.target.name,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
var result = [];
var total = 0;
for (var key in selections) {
var listItem = "<li>" + selections[key].name + " " +
selections[key].value + "</li>";
result.push(listItem);
total += parseInt(selections[key].value.substring(1));
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join("");
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p>Selected Seat(s)</p>
<!-- container for displaying selected seats -->
<ul id="selected-seats"></ul>
<div>
Total: $<span id="seats-total">0</span> USD
<input type="submit" value="Reserve Now">
</div>
</form>
</body>
</html>
How do I add event listeners to check the number of checkboxes selected on a page and display an alert?
You can do so by checking number of ticked boxes whenever a user clicks on the box.
You can read the comments in the code to better understand it
// Defind how many check boxes a user can check
// You requested 5 but to make it less html code, I put 2 in the variable below
var checkboxLimit = 2;
// Get every check box by using querySelectorAll
document.querySelectorAll("input[type=checkbox]").forEach(
// For each check box add on click event listener
input => input.addEventListener('click', function(event) {
// get number of check boxes by passing :check attribute to the query selector
var numberTickedBoxes =
document.querySelectorAll("input[type=checkbox]:checked").length;
// check if the number of ticked boxes are more than allowed limit
if(checkboxLimit < numberTickedBoxes){
alert("You are allowed to check " + checkboxLimit + " boxes")
}
})
);
<label>1</label>
<input type="checkbox" name="test" value="1" />
<br/>
<label>2</label>
<input type="checkbox" name="test" value="2" />
<br/>
<label>3</label>
<input type="checkbox" name="test" value="3" />
<br/>
Adding an eventListener to each checkbox
Either select all and loop over the collection and add the events to each element in the collection.
var cbs = document.querySelectorAll('[type="checkbox"]');[].forEach.call(cbs, function (cb) { cb.addEventListener("click", function(){ console.log(this.id); });});
<div id="wrap"> <div id=""> <input name="checkboxopt" id="checkboxopt" value="true" type="checkbox"> </div> <div id=""> <input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox"> </div> <div id=""> <input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox"> </div></div>
Javascript checkbox onChange
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
Remove Event Listener from Checkbox Using Input Type?
I'd add the checked boxes to a Set and add/delete them from the Set on click. Check whether they're already in the set to determine whether you need to add or subtract from the sum.
const clickedCheckboxes = new Set();
let sum = 0;
const priceDiv = document.getElementById("price");
document.addEventListener("click", ({ target }) => {
if (!target.matches("input[type=checkbox]")) {
return;
}
if (clickedCheckboxes.has(target)) {
clickedCheckboxes.delete(target);
sum -= target.value;
} else {
clickedCheckboxes.add(target);
sum += Number(target.value);
}
priceDiv.textContent = `Food Total: $${(sum / 100).toFixed(2)}`;
});
Related Topics
Html5 Canvas Ctx.Filltext Won't Do Line Breaks
Anchor Jumping by Using JavaScript
How to Change a <Select> Value from JavaScript
Html5 Audio Tag on Safari Has a Delay
Document.Getelementsbyclassname().Innerhtml Always Returns "Undefined"
How to Determine If a Checkbox Is Checked
How to Auto-Submit an Upload Form When a File Is Selected
How to Dynamically Scale Text Size Based on Browser Width
How to Get the HTML of a Div on Another Page with Jquery Ajax
Angularjs: Better Way to Watch for Height Change
Html5 Filereader How to Return Result
Play .Wav Sound File Encoded in Base64 with JavaScript
What Is the Correct Way to Check for String Equality in JavaScript
Capture Frames from Video with HTML5 and JavaScript
Getting a Better Understanding of Callback Functions in JavaScript