javascript - Trigger event when any checkbox is checked/unchecked - javascript

In my HTML, I have a lot of checkboxes.
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
(Even more checkboxes ..............)
Without jQuery, how do I create an alert once any checkbox in the document is changed?
(With so many checkboxes, it will be very troublesome to add onclick="alert('Hello!');" on every single checkbox.)

This is how you would do it without jQuery:
// get all the checkboxes on the page
var checkboxes = document.querySelectorAll('input[type=checkbox]');
// add a change event listener
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(){
console.log('the checkbox changed');
});
}
Note: document.querySelectorAll is not supported in IE7 or below.
http://caniuse.com/queryselector

Clicks are bubbling through the document, you could use a single eventlistener for the parent element of these inputs. Something like this:
<form id="form">
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
</form>
JS:
document.getElementById('form').addEventListener('click', function (e) {
if (e.target.type === 'checkbox') {
alert('Checkbox');
}
});
If you don't have a form or any other common parent element (and you don't want to add a one), you can add the listener to the document as well.
A live demo at jsFiddle.

you can do like this :
HTML:
<form id="form">
<input type="checkbox" name="checkbox" /> Check me!
<input type="checkbox" name="checkbox"/> Check me as well!
<input type="checkbox" name="checkbox"/> Check me too!
<input type="checkbox" name="checkbox"/> This is a checkbox.
<input type="checkbox" name="checkbox"/> It is not a radio button.
<input type="checkbox" name="checkbox"/> Just saying.
</form>
JS:
var cbobject= document.forms[0].elements.checkbox;
for (var i=0, len=cbobject.length; i<len; i++) {
if ( cbobject[i].type === 'checkbox' ) {
cbobject[i].onclick = show_alert;
}
}
function show_alert(e){
alert("checkbox!!!")
}
DEMO:

Related

Read Only Text Column With Checkbox

I made a very easy one HTML input column. I added JavaScript to it with a checkbox in it.
When I clicked check box checked I want write the text or unchecked the text box read only how to solve my problem. Give for example for my code
<input type="text" id="inputID" value="abc"></input>
<input type="checkbox" id="myCheck" checked>
<script>
document.getElementById('inputID').readOnly = true;
</script>
Add an event listener to the change event on the checkbox.
<input type="text" id="inputID" value="abc" readonly></input>
<input type="checkbox" id="myCheck" >
<script>
var checkbox = document.getElementById('myCheck');
checkbox.addEventListener('change', function() {
document.getElementById('inputID').readOnly = !this.checked;
});
</script>
Working fiddle

Uncheck a checkbox when another is checked

function uncheck() {
var notTest = document.getElementById("choice_31_3_2");
var Test = document.getElementById("choice_31_3_1");
if (notTest.checked) {
Test.checked = false;
}
if (Test.checked) {
notTest.checked = false;
}
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
I wrote a function to uncheck a checkbox if another one is checked, I am using jQuery to call uncheck() on those specific input.
I am getting the result I want. When I check test then check notTest, Test is being unchecked. BUT when I am pressing Test again, the test checkbox is refusing to check unless I manually uncheck notTest.
I included the code snippet , please can figure out what is wrong ?
The code is running normally on Wordpress but unfortunately not here.
Here you go with a solution
$('input[type="checkbox"]').change(function(){
console.log($(this).is(':checked'));
if($(this).is(':checked')){
$(this).siblings('input[type="checkbox"]').attr('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Hope this will help you.
You can code like this,
HTML:-
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
JQUERY:-
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
Working Demo url
Hope this will help you.
BUT when i am pressing Test again, the test checkbox is refusing to
chech unless i manually uncheck notTest.
It is because when you press again, you didn't check which checkbox you have clicked on. You simply unchecked a checked-checkbox.
Try this simple approach
var allIds = [ "choice_31_3_1", "choice_31_3_2" ];
function uncheck( event )
{
var id = event.target.id;
allIds.forEach( function( id ){
if ( id != event.target.id )
{
document.getElementById( id ).checked = false;
}
});
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Try this.
$('input.test').on('change', function() {
$('input.test').not(this).prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox" class="test">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox" class="test">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Using JS: Change your function to this:
$(function(){
function uncheck(e) {
var isElemChecked = e.target.checked;
// Return if the element was being unchecked
if(!isElemChecked){
return;
}
$('input').prop('checked',!isElemChecked);
$(e.target).prop('checked',isElemChecked);
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
})
Using CSS (no need for JS code):
Change your inputs to type=radio and update the css as
input[type="radio"] {
-webkit-appearance: checkbox; /* Chrome, Safari, Opera */
-moz-appearance: checkbox; /* Firefox */
}
<input name="input_3" value="Test" id="choice_31_3_1" type="radio">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3" value="notTest" id="choice_31_3_2" type="radio">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Please note CSS approach would not work on IE.
https://plnkr.co/edit/o7dft84Cm4tA3GUOLt4y?p=preview
function uncheck() {
if (this.checked){ // support unchecking
$('input').prop('checked',false);
this.checked = true
}
}
You have to know which element triggered the event in order to solve it properly.
One way to solve it is the function I show above - simply mark all checkboxes to false, then mark this - the element that triggered the event - to true.

changing the checked attribute of checkbox using jquery

I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo

CSS is not changing through calling JS in HTML

my JS code is bellow:
// JavaScript Document
function bubbleColor() {
if($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked"))
{
$(".bubble").css("background-color", "red");
}
}
var el = document.getElementById(".bubble");
el.onclick = bubbleColor;
And my targeted HTML:
<div id="circle" class="bubble">
<p class="circle_text">
#6
</p>
</div>
<br/><br/>
<input type="checkbox" value="1" id="Checkbox1" name="Checkbox1"/> Answer one <br/>
<input type="checkbox" value="1" id="Checkbox2" name="Checkbox2"/> Answer two <br/>
<input type="checkbox" value="1" id="Checkbox3" name="a3"/> Answer three <br/>
Desired output:
When somebody checks [selects] both the Checkbox1 and Checkbox2, the #6 background should be Red color.
Problem:
The code does not seem to work.
Any help please?
Im assuming you are using jquery (as you are changing css with jquery)
The behaviour you describe in your question implies that changing the checkbox should trigger a verification, so why do you attach the bubbleColor function to clicking on the .bubble div?
Try something like this:
// Alternatively you could use a class to select the checkboxes
$("input[type='checkbox']").change(bubbleColor);
Ofcourse ideally you should change your function to remove the red color if you uncheck the boxes:
function bubbleColor() {
if ($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked")) {
$(".bubble").css("background-color", "red");
} else {
$(".bubble").css("background-color", "transparent");
}
}
Fiddle: http://jsfiddle.net/sQCcF/2/
Edit:
If what you want is to ensure user only selects 1 option then you should use radio buttons instead of checkboxes, as that is the default behavior:
<input type="radio" name="inputname" value="1"/>
<input type="radio" name="inputname" value="2"/>
<input type="radio" name="inputname" value="3"/>
The name has to be the same for the inputs, but each one will have a different value, selecting one will automatically unselect the other.
Problem is at
var el = document.getElementById(".bubble");
You are selecting element with ID of .bubble (bubble is a class)
Change it to and check :
var el = document.getElementById("circle");
First of all you attach an event handler for the click event on div with class "bubble".
Then, you use document.getElementById method to select an element but you use as argument the class of that element, not the ID.
For this to work you need to attach the click event handler to checkbox elements.
Something like this:
$('input[type="checkbox"]').click(function() {
bubbleColor();
});
Replace var el = document.getElementById(".bubble");
el.onclick = bubbleColor;
with
$(".bubble").click(bubbleColor) ;
should work.
Try this code
HTML
<div id="circle" class="bubble">
<p class="circle_text">
#6
</p>
</div>
<br/><br/>
<input type="checkbox" value="1" id="Checkbox1" name="Checkbox1" class="chBox"/> Answer one <br/>
<input type="checkbox" value="1" id="Checkbox2" name="Checkbox2" class="chBox" /> Answer two <br/>
<input type="checkbox" value="1" id="Checkbox3" name="a3" class="chBox" /> Answer three <br/>
JQUERY
$(document).ready(function(){
// you can use '.chBox class or input[type='checkbox']'
$('.chBox').bind('click', function(){
if($("#Checkbox1").is(":checked") && $("#Checkbox2").is(":checked"))
{
$(".bubble").css("background-color", "red");
}else{
$(".bubble").css("background-color", "#fff");
}
});
});

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources