Checkbox Check Event Listener - javascript

Recently I have been working with the Chrome Plugin API and I am looking to develop a plugin which will make life easier for me for managing a website.
Now what I wish to do is to fire an event when a certain checkbox is checked.
As this website does not belong to me I cannot change the code therefore I am using the Chrome API. One of the main problems is that rather than there being an ID, there is a Name. I was wondering if I could fire the function once the certain checkbox with the 'name' is checked.

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" />
Single checkbox with jQuery
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
Multiple checkboxes
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
Multiple checkboxes with jQuery
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>

Since I don't see the jQuery tag in the OP, here is a javascript only option :
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE

If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});

Related

onchange don't work on checkbox when there are multiple check

I have many checkbox with onchange event that change line color where is checked :
<input type="checkbox" onchange="cocheCommande($(this))" name="${NAME_SELECTION}" value="<%=command.getCdeId()%>" />
function cocheCommande(chk)
{
alert("test cocheCommande");
var tr=chk.closest('tr');
if (chk.is(':checked'))
{
tr.css('background','#33EE33');
tr.nextUntil("tr.entete","tr").css('background','#FFFF33');
}
else
{
tr.css('background','#D0EED0');
tr.nextUntil("tr.entete","tr").css('background','#EEEED0');
}
}
I have a function that allows to check everything or uncheck. But if I use, onchange event is never call even though everything is checked.
Why ? And how can I do ?
As others said, you can't use $ in the html template; you can, however, pass this as the argument to your onchange handler:
HTML:
<input onchange="change(this)" type="checkbox" />
JS:
function change(elem) {
var element = $(elem);
console.log(element.next())
}
https://plnkr.co/edit/dx8GoJxHwKa52VFCkn2G?p=preview

Javascript check box to uncheck other boxes and vice versa

I have the following set of checkboxes:
Original:
<INPUT TYPE="checkbox" ID="db1" class="db" checked>
<INPUT TYPE="checkbox" ID="db2" class="db" checked>
<INPUT TYPE="checkbox" ID="db3" class="db" checked>
<INPUT TYPE="checkbox" ID="db4" class="db" checked>
</br>
Other:
<INPUT TYPE="checkbox" ID="other" class="other" onclick="otherBoxes('other',this)">
and the following javascript:
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function otherBoxes(it,box)
{
$(function()
{
$(':checkbox').click(function()
{
if (this.checked)
{
$('.db').prop('checked',false);
}
}
)
}
)
}
</script>
What I am trying to do is set someting up so that when I check the 'other' checkbox, the 'Original' checkboxes are all unchecked.
I then want to have the reverse, so that if one (or more) of the 'Original' checkboxes are checked, the 'other' checkbox is unchecked.
The Javascript I have so far kind of does the first part of this, in that if I check, then uncheck, then check the 'other' box again, the 'Original' boxes are unchecked.
However, I would like it to work when the box is checked the first time.
It also has the unintended consequence, that after the 'other' box has been checked, the 'original' boxes refuse to be checked, even if I uncheck the 'other' box.
I've found lots of examples of similar situations, but none the same, and I haven't been able to adapt any that I have found. How can I do this please?
You can try something like that
$('.other').on('click' , function() {
$('.db').each(function(){
$(this).removeAttr('checked');
})
});
$('.db').on('click', function(){
$('.other').removeAttr('checked');
});
here it is a working jsfiddle http://jsfiddle.net/vQTFm/
P.S. : I suggest you to avoid using similar names beetwen ids and classs because it CAN be confusing.
You should bind the events using jQuery instead of in the HTML.
Here is some code that does what you want, it binds to the change event on the checkboxes and then checks whether it was the other or db checkboxes that were checked and unchecks the required check-boxes:
$(function() {
$('.db, #other').on('change', function() {
if (this.checked) {
if ($(this).is('#other')) {
$('input:checkbox').not('#other').prop('checked', false);
} else {
$('#other').prop('checked', false);
}
}
});
});
Working example - http://jsfiddle.net/YD5SE/2/
Use the following JS code:
<script type="text/javascript">
function otherBoxes(it,box)
{
if (box.checked)
{
$('.db').prop('checked',false);
}
}
</script>

Optimize jQuery small script for checkboxes

I made a small verification script which is supposed to act like this:
I have 4 checkboxes, one has a particular way of action, the id of this checkbox is chx0
If I checked the chx0 checkbox then it released all the others checked checkboxes
If I checked one of all the others checkboxes then it released the chx0 one
Here is my code:
<script type="text/javascript">
$(document).ready(function() {
$('#chx0').click(function() { // click on the chx0 checkbox
if ($('#chx0').attr('checked')) {
$('#chx1').attr('checked', false);
$('#chx2').attr('checked', false);
$('#chx3').attr('checked', false);
}
});
$('#chx1').click(function() {// click on the chx1 checkbox
if ($('#chx1').attr('checked')) {
$('#chx0').attr('checked', false);
}
});
$('#chx2').click(function() { // click on the chx2 checkbox
if ($('#chx2').attr('checked')) {
$('#chx0').attr('checked', false);
}
});
$('#chx3').click(function() { // click on the chx3 checkbox
if ($('#chx3').attr('checked')) {
$('#chx0').attr('checked', false);
}
});
});
</script>
This code is working pretty well it just to get more good practice!
I'd put a class on each checkbox
<input type="checkbox" name="chx0" id="chx0" class="checkbox-group singleton">
<label for="chx0">Check me out!</label>
<input type="checkbox" name="chx1" id="chx1" class="checkbox-group">
<label for="chx1">Check us out!</label>
<input type="checkbox" name="chx2" id="chx2" class="checkbox-group">
<label for="chx2">Check them out!</label>
Then with your jQuery you can do
$('input.checkbox-group').each( function() {
$(this).click( function() {
if ( $(this).hasClass('singleton') ) {
$('input.checkbox-group:checked').removeAttr('checked');
} else {
$('input.checkbox-group.singleton').removeAttr('checked');
}
};
});
Untested, but I think something like that should work. I can't remember if it's better to use the change event rather than click.
You could combine the clauses for all the individual checkboxes, something like
$('#chx1','#chx2','#chx3').click(function() {
if ($(this).attr('checked')) {
$('#chx0').attr('checked', false);
}
});
instead of one per checkbox. Also in the one for "chx0", you can use $(this) instead of $('#chx0')
I came up with something similar to ianbarker. Rather than assume dependencies are all or nothing I used a custom data tag to list the dependencies.
A working example is on jsfiddle here
$('.luckyChecks').click(function() { // click on ANY lucky checkbox
var $t = $(this);
if($t.attr('checked')){
var clear = $t.attr("data-clear").split(",");
for(var i=0; i < clear.length; i++){
$('#'+clear[i]).attr('checked',false);
}
}
});
HTML:
<input type="checkbox" id="chx0" class="luckyChecks" data-clear="chx1,chx2,chx3" />
Diamonds <br />
<input type="checkbox" id="chx1" class="luckyChecks" data-clear="chx0"/>
Clovers <br />
...

check/uncheck radio input with javascript

I have a radio input group. If a radio is checked and I click again it becomes unchecked.
Is there a way to get the previous status of the radio onClick event?
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
jQuery edition
// bind to retrieve old status
$('input[type="radio"]').mousedown(function() {
// if it was checked before
if(this.checked) {
// bind event to reset state after click is completed
$(this).mouseup(function() {
// bind param, because "this" will point somewhere else in setTimeout
var radio = this;
// apparently if you do it immediatelly, it will be overriden, hence wait a tiny bit
setTimeout(function() {
radio.checked = false;
}, 5);
// don't handle mouseup anymore unless bound again
$(this).unbind('mouseup');
});
}
});
But again, this is not how radio buttons are intended to be used. I think you'd be better of with a set checkbox'es where you could uncheck all other checkboxes than the current clicked (hence always max 1 selected)
A working example
I use this. You simply store the pre-click value and ! it into the value.
<input type=radio name="myoptions" value="1"
onmousedown="this.tag = this.checked;" onclick="this.checked = !this.tag;">
This behavior is not the expected one for radio buttons and I don't recommend it at all. Try to find another way of achieving this. Use another widget or another option to reset the field value:
http://jsfiddle.net/marcosfromero/rRTE8/
try this:
function resetMeIfChecked(radio){
if(radio.checked && radio.value == window.lastrv){
$(radio).removeAttr('checked');
window.lastrv = 0;
}
else
window.lastrv = radio.value;
}
<input value="1" name="options" checked="checked" type="radio" onClick="resetMeIfChecked(this)" />A
<input value="2" name="options" type="radio" onClick="resetMeIfChecked(this)" />B
<input value="3" name="options" type="radio" onClick="resetMeIfChecked(this)" />C
Its quite simple. Just follow the simple example and
var rdblength=document.formname.elementname.length;
alert('length='+rdblength);
for(i=0;i<rdblength;i++){
document.formname.elementname[i].checked=false;
}
Just find the length and make every index checked=true/false.
Ping me at:-
http://manojbardhan2009.blogspot.com
I had the same problem and figured it out. None of the answers above work exactly as I wanted - most of them require an additional button to reset the radio. The goal was to uncheck radio by clicking on the radio itself.
Here's the fiddle: http://jsfiddle.net/MEk5Q/1/
The problem was very complicated because the radio button value changes BEFORE the click event fires so when we're listening to the event we can't tell if the radio button was already checked or not. In both cases it is already checked.
Another approach was to listen to mousedown event. Unlike click, it fires before changing radio checked attribute but unchecking it inside event handler gives us nothing since it is checked back again during mouseup event.
My answer is a little ugly workaround so I generally don't suggest it to others and I'll probably abandon it myself. It works but it involves 20ms timeout function which I'm not fond of in cases like this.
Here is the code explanation:
$('input[type="radio"]').on('mousedown', function() {
if (this.checked) { //on mousedown we can easily determine if the radio is already checked
this.dataset.check = '1'; //if so, we set a custom attribute (in DOM it would be data-check="1")
}
}).on('mouseup', function() {
if (this.dataset.check) { //then on mouseup we determine if the radio was just meant to be unchecked
var radio = this;
setTimeout(function() {radio.checked = false;}, 20); //we give it a 20ms delay because radio checking fires right after mouseup event
delete this.dataset.check; //get rid of our custom attribute
}
});
As a timeout function I could use a string (less writing) but as far as I know it would be eval'ed. Though I don't trust eval function, I prefered anonymous function.
One more thing - one could ask why spreading the code into two separate event handlers while we can fire the timeout function on mousedown? Well, what if someone press the mouse on a radio and holds it for a few secs or even someone is simply a very slow person ;). Generally, with this solution we omit the problem of lag between mousedown and mouseup.
If you need some more info about dataset, here's the MDN reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
This property came with HTML5 and might be not cross-browser, I guess, so if you want 100% compatibility, replace it with any other solution that'll contain the data, you name it.
Sorry about jQuery here and there but I hope you're fine with it - it was much easier that way.
Hope you'll enjoy it.
$('input[type="radio"]').on("mousedown", function () {
if (this.checked) {
$(this).one("click", function () {
this.checked = false;
});
}
});
I was never too happy about being forced to aim at that tiny radio button, so I came up with a larger target AND a way to turn a radio group off without resorting to anything that would upset the HTML / JavaScript purists.
The technique relies on not molesting the radio buttons at all via event handlers, but checking for a readonly proxy for each one instead. Everything is contained in what's below in pure JavaScript using a radio group to select a type of cheese, or no cheese at all.
I purposely used no styling in this example to avoid that added layer. The dump button will tell you what the three checked states are, so use it to interrogate what happened after hitting the radio or text input elements. For example simplicity I used a global to remember the former state, but a more elegant method is to use a dataset, which I what I use in the real code of my application.
<!DOCTYPE html>
<html>
<head>
<title>Uncheck a radio button</title>
<script>
function attachEventListener(target, eventType, functionRef, capture) {
"use strict";
if (typeof target.addEventListener !== 'undefined') {
// Most modern browsers
target.addEventListener(eventType, functionRef, capture);
} else if (typeof target.attachEvent !== 'undefined') {
// IE
target.attachEvent('on' + eventType, functionRef);
} else {
eventType = 'on' + eventType;
if (typeof target[eventType] === 'function') {
var oldListener = target[eventType];
target[eventType] = function() {
oldListener();
return functionRef();
};
} else {
target[eventType] = functionRef;
}
}
}
</script>
</head>
<body>
<form>
<input id="Cheddar-radio" class="radio" type="radio" name="Cheeses-0" value="Cheddar Cheese" tabindex="-1"></input>
<input id="Cheddar-text" type="text" readonly value="Cheddar Cheese" tabindex="-1"></input><br>
<input id="Swiss-radio" class="radio" type="radio" name="Cheeses-0" value="Swiss Cheese" tabindex="-1"></input>
<input id="Swiss-text" type="text" readonly value="Swiss Cheese" tabindex="-1"></input><br>
<input id="American-radio" class="radio" type="radio" name="Cheeses-0" value="American Cheese" tabindex="-1"></input>
<input id="American-text" type="text" readonly value="American Cheese" tabindex="-1"></input><br><br>
<input onclick="dumpStates()" type="button" name="button" value="dump" tabindex="-1"></input>
</form>
<script>
window.onload = addRadioListeners;
function addRadioListeners() { // But do it on the -text elements.
attachEventListener(document.getElementById('Cheddar-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('American-text'), 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Cheddar-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('American-text'), 'mouseup', checkNewState, false);
}
function dumpStates() {
console.log(document.getElementById('Cheddar-radio').checked +
' ' + document.getElementById('Swiss-radio').checked +
' ' + document.getElementById('American-radio').checked);
}
var elementWasChecked; // Global - Could just as well use a dataset attribute
// on either the -radio or -text element and check it instead.
function rememberCurrentState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
elementWasChecked = radioElement.checked;
radioElement.checked = true;
}
function checkNewState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
var currentState = radioElement.checked;
if (elementWasChecked === true && currentState === true) {
console.log('Changing ' + radioElement.id + ' to false.');
radioElement.checked = false;
}
};
</script>
</body>
</html>
If you click on the radio buttons they work as expected. If you click on the text items next to each, they are a proxy for the radio buttons with one exception. If you click on a text item that has an associated radio button that's already checked, it will uncheck it. Therefore, the text proxy's are event triggered, and not the radio buttons.
The added benefit is that you can now hit the larger text target too.
If you want to make it simple and wouldn't mind using a double-click event try something like this:
<input name="options" type="radio" ondblclick="this.checked=false;">
#jerjer's answer is almost perfect, but radios can be switched also by arrows if the radio group has the focus (so mousedown event is not enough). Alas, the radio group also gets checked when activated by focus shift (Tab), which can undesirably check one option. Therefore space should uncheck the focused radio, just like the checkbox behavior.
This code fixes that for all radios (Most credit still goes to jerjer):
window.addEventListener("DOMContentLoaded", function() {
var radios = document.querySelectorAll("input[type=radio]");
for(var i=0; i<radios.length; ++i) {
radios[i].addEventListener("click", function(e) {
if(e.target.checked && e.target.value == window.lastrv){
e.target.checked = false;
window.lastrv = 0;
}
else
window.lastrv = e.target.value;
});
radios[i].addEventListener("keypress", function(e) {
if(e.keyCode==32) e.target.click();
});
}
});

Given a checkbox object output its value

I have a page that has a number of checkboxes in it. I would like to write a function that will be called when the ckeckbox is clicked, that determines if the checkbox is checked or not.
<input type="checkbox" onclick="toggleVis('id', this);"/> ID
<input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit
<input type="checkbox" onclick="toggleVis('last', this);"/> Last
Note some checkboxes start checked.
I figured that there must be a way to do this based on a reference passed, so I passed the this value as a parameter.
function toggleVis(name, checkbox)
{
//if(checkbox.checked())
console.log('checked');
if($('.'+name).css('display') != "none")
$('.'+name).css('display', 'none');
else
$('.'+name).css('display', 'table-cell');
}
I am open to use jQuery.
You were close.
if(checkbox.checked) {
console.log('checked');
//...
}
There's no checked() method, but there is a checked property. Note that your code may only work on clicks. Perhaps onchange would be better?
Look at the checkboxobj.checked property (instead of calling it like a function). In your case, you could reference if (checkbox.checked) { ... }. More information can be found on this website
If you wanted to do this with jQuery you might try the following. Note that I'm binding to the checkbox instead of including the 'onclick' or 'onchange' directly on the HTML element.
$('[type=checkbox]').click(function(){
if( $(this).attr('checked') ){
console.log('checked');
if($('.'+$(this).attr('name')).css('display') != "none") {
$('.'+$(this).attr('name')).css('display', 'none');
} else {
$('.'+$(this).attr('name')).css('display', 'table-cell');
}
}
});
And a JQuery-based solution:
var checked = $(checkbox).is(':checked');
Helpful if you want to find the checkbox first by some JQ selector.
<input type="checkbox" class="checkthis"> ID
<input type="checkbox" class="checkthis" checked="checked"> Edit
<input type="checkbox" class="checkthis"> Last
$(input.checkthis).click(function() {
if($(this).is(':checked') {
// do checked stuuf
} else {
// do not checked stuff
}
});

Categories