How to apply checkbox with functions in javascript?
How to hide post/object with specific tags when checkbox is unchecked?
I just need to know how to put functions for the checkbox to be automatically check upon opening the page and the checkbox to hide posts/objects with a specific tag on them. Is it correct to apply--
display:none
or--
.structural {
position:absolute;
left:-9999px;
}
--that I've found during research?
This was as far as I could go considering my lack of skills:
<input
type="checkbox"
name="mycheckbox"
value="yes"
onclick=" CheckboxChecked(this.checked,'checkboxdiv')"
</div>
</div>
<script type="text/javascript">
CheckboxChecked(document.myform.mycheckbox.checked,'checkboxdiv');
</script>
If I understood your question correctly, you are attempting to hide/show a group of elements when a checkbox is checked/unchecked. This should be enough to get you going:
http://jsfiddle.net/HsCVq/
HTML:
<div class="hideWhenChecked">hide text</div>
<div>dont hide text</div>
<div class="hideWhenChecked">hide text</div>
<div>dont hide text</div>
<br />
<input type="checkbox" id="myCheckBox" />
JavaScript:
document.getElementById('myCheckBox').addEventListener('click', function () {
var checked = this.checked;
var elementsToHide = document.getElementsByClassName('hideWhenChecked');
if (checked) {
// hide each element
} else {
// show each element
}
});
I'd suggest looking into a javascript framework such as jQuery to make this code a lot simpler.
With jQuery
Something like this is pretty trivial with jQuery:
$("form").on("click", ":checkbox[name^='toggle_']", function(event){
$( "#" + event.target.name.split('_')[1] )
.toggle( event.target.checked );
});
But you shouldn't use jQuery just for something like this - that would be overkill.
Old-fashioned JavaScript, the way your Grandfather did it.
Here's a quick implementation (tested in IE7+). It works by extracting the corresponding element to hide from the name of the checkbox being clicked.
<form name="myform">
<input name="toggle_checkBox" type="checkbox" checked />
<div id="checkBox">
If checked, you'll see me.
</div>
</form>
This checkbox, when clicked will hide the DIV below it.
var myform = document.forms.myform;
var inputs = myform.getElementsByTagName("input");
function toggleElement () {
var e = event.target || window.event.srcElement;
var display = e.checked ? "" : "none" ;
document.getElementById( e.name.split('_')[1] ).style.display = display;
}
for ( var i = 0; i < inputs.length; i++ ) {
var chk = inputs[i];
if ( chk.type == "checkbox" && /^toggle_/.test( chk.name ) ) {
if ( chk.addEventListener ) {
chk.addEventListener("click", toggleElement, false);
} else if ( chk.attachEvent ) {
chk.attachEvent("onclick", toggleElement);
}
}
}
Demo: http://jsbin.com/ibicul/5
Have a look at this
HTML:
<form>
<!-- for keeping checkbox checked when page loads use checked="checked" --->
<input type="checkbox" name="check" onclick="toggle(this.form.check);" checked="checked">
<input type="checkbox" name="check1"/><br>
<br>
</form>
<!-- the id of this element is used in script to set visibility --->
<div id="text" style="visibility:hidden">
My visibility is based on checkbox selection
</div>
Script
<script>
function toggle(check)
{ if(!check.checked)
{
document.getElementById('text').style.visibility='visible';
}
else
{
document.getElementById('text').style.visibility='hidden';
}
}
</script>
This should work :)
Related
I was wondering if there was a better way to go about enabled/disabled multiple checkboxes at once.
In the html I have two radio buttons to choose between all hair options and custom hair options, having the default all one disable the checkboxes while the custom one enables them.
This is what I've got so far that works (probably looks dumb, I apologize), but I'd like to know if there's a more efficient way to go about this? I'd like to do it as "small" as possible while still being easily readable/understandable for my own sake.
function checkHaOp(){
if (document.getElementById("hairOptionAll").checked){
document.getElementById("hairAuburn").disabled = true;
document.getElementById("hairBlack").disabled = true;
document.getElementById("hairBlonde").disabled = true;
document.getElementById("hairBrown").disabled = true;
document.getElementById("hairRed").disabled = true;
document.getElementById("hairOther").disabled = true;
}
else if (document.getElementById("hairOptionCustom").checked){
document.getElementById("hairAuburn").disabled = false;
document.getElementById("hairBlack").disabled = false;
document.getElementById("hairBlonde").disabled = false;
document.getElementById("hairBrown").disabled = false;
document.getElementById("hairRed").disabled = false;
document.getElementById("hairOther").disabled = false;
}
}
Preferably using javascript since I don't know jquery.
I'd also appreciate explanations of things since I am still learning.
You can add/use class like said #NiettheDarkAbsol
then something like that.
var inpck = document.getElementsByClassName("input-checkbox");
if (document.getElementById("hairOptionAll").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = true;
}
}
if (document.getElementById("hairOptionCustom").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = false;
}
}
Now your turn to refactor this :D
You can use
document.querySelectorAll('[id^=hair]')
It selects all elements that has an id which starts with "hair"
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="hairOptionAll">
<input type="checkbox" id="hairAuburn">
<input type="checkbox" id="hairBlack">
<input type="checkbox" id="hairBlonde">
<input type="checkbox" id="hairBrown">
<input type="checkbox" id="hairRed">
<input type="checkbox" id="hairOther">
</body>
<script>
const hairCb = document.querySelectorAll('[id^=hair]');
for (let i=0; i<hairCb.length; i++) {
hairCb[i].disabled = true;
}
</script>
</html>
Here's the optimized solution.
<div class="radio-btns">
All <input type="radio" id="hairOptionAll" name="hairOptionAll"/>
Custom <input type="radio" id="hairOptionCustom" name="hairOptionCustom"/>
</div>
<div class="hairOptions">
hairAuburn <input type="checkbox" id="hairAuburn" />
hairBlack <input type="checkbox" id="hairBlack" />
hairBlonde <input type="checkbox" id="hairBlonde" />
hairBrown <input type="checkbox" id="hairBrown" />
hairRed <input type="checkbox" id="hairRed" />
hairOther <input type="checkbox" id="hairOther" />
</div>
<script type="text/javascript">
const radioBtns = document.querySelector('.radio-btns');
radioBtns.children[0].checked = true;
radioBtns.addEventListener("click", (event) => {
radioBtns.children[0].checked = (event.target.id == 'hairOptionAll') ? true : false;
radioBtns.children[1].checked = (event.target.id == 'hairOptionCustom') ? true : false;
const allOptions = [...event.target.parentElement.nextElementSibling.children];
allOptions.map(option => ( option.checked = (event.target.id == 'hairOptionCustom') ? true : false ) );
});
</script>
Here is a complete working code you. To minimise the code we write to we need to use a class selector not an id - Give the same class to your radio button and then use a forEach loop to go through all the radio button. Add the class to your checkboxes as well.
To get all the checkboxes we can use forEach method.
Once you have all the radio button you need to listen for a change on a particular radio button and then we will check whether the radio button we have selected is checked and its id is all or custom.
To get the id of the actual radio button which was clicked we can use getAttribute method which return the id of checked radio button.
If our condition matches we will disable all the checkboxes or if its else then we enable all the checkboxes using forEach loop on the checkbox classes.
We will pass true or false as an argument to disable checkboxes function to avoid having have two loops
Live Working Example (I have added notes / comment on each line of code for your understanding as well)
//Enable disable checkbox
function disableChekbox(isChecked) {
let getHairOptions = document.querySelectorAll('.hairOptions') //get all checkboxes
getHairOptions.forEach(function(x) {
x.disabled = isChecked
})
}
let getHairRadio = document.querySelectorAll('.hairOptionAll') //get all radio buttons
//For each all radio buttons
getHairRadio.forEach(function(radio) {
//listen to change on radio
radio.addEventListener('change', function(e) {
if (e.target.checked && e.target.getAttribute('id') == 'hairOptionAll') {
//loop through all checkboxes
disableChekbox(true)
} else if (e.target.checked && e.target.getAttribute('id') == 'hairOptionCustom') {
//loop through all checkboxes
disableChekbox(false)
}
})
})
All <input type="radio" id="hairOptionAll" name="hairOptionAll" class="hairOptionAll" />
Custom <input type="radio" id="hairOptionCustom" name="hairOptionAll" class="hairOptionAll" />
<br>
<br>
hairAuburn <input type="checkbox" id="hairAuburn" class="hairOptions" />
hairBlack <input type="checkbox" id="hairBlack" class="hairOptions" />
hairBlonde <input type="checkbox" id="hairBlonde" class="hairOptions" />
hairBrown <input type="checkbox" id="hairBrown" class="hairOptions" />
hairRed <input type="checkbox" id="hairRed" class="hairOptions" />
hairOther <input type="checkbox" id="hairOther" class="hairOptions" />
First of all: http://jsfiddle.net/1q5st19f/
I have a checkbox group where if all the child checkboxes (countries) are checked, the parent checkbox (region) becomes checked as well. Likewise, if the parent checkbox is unchecked, the child checkboxes should be unchecked, too. I found a script that worked perfectly until I styled the checkboxes with prettyCheckable (from http://arthurgouveia.com/prettyCheckable/).
If I remove prettyCheckable, it works. If I add it, it's correctly styled but won't work anymore. What am I doing wrong? I tried to rename the classes but that didn't work either.
The basic markup is like
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label=""> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label=""> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label=""> Benin<br />
</div>
</fieldset>
prettyCheckable made this a bit tricky. It says in the documentation that you can use $('#myInput').prettyCheckable('check'); but I could not get it to work. So I just used the anchors class checked instead to determine if the checkbox is checked.
This may not be the most pretty implementation but it's working. You should make the code more modular an maybe reconsider some of the choices I quickly made.
First I removed the childCheckBox from the HTML and initialized prettyCheckable with options, so I could get the class to the wrapper div:
// make childCheckboxes prettyCheckable
$('.content input:checkbox').each(function () {
$(this).prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "childCheckBox"
});
});
Same with the parentCheckbox:
// make parentCheckBox prettyCheckable
$('input:checkbox.parentInput').prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "parentCheckBox"
});
I also changed childCheckBox click event to do the functionality you wanted
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(function () {
var $parentAnchor = $(this).parents('fieldset:eq(0)').find('.parentCheckBox a');
var $childAnchors = $(this).parents('fieldset:eq(0)').find('.childCheckBox a');
var $thisAnchor = $(this).find('a');
var parentIsChecked = $parentAnchor.hasClass('checked');
var thisIsChecked = $thisAnchor.hasClass('checked');
var isLastOne = true;
// loop through all childCheckBoxes and determine if this is the last one checked or unchecked
$childAnchors.each(function (index) {
if ((!thisIsChecked && $(this).hasClass('checked'))
|| (thisIsChecked && !$(this).hasClass('checked'))) {
isLastOne = false;
}
});
// if the childCheckBox was the last one, change the state of the parentCheckBox
if (isLastOne && thisIsChecked) {
$parentAnchor.addClass('checked');
} else if (isLastOne && !thisIsChecked) {
$parentAnchor.removeClass('checked');
}
});
I was pretty tired when forking this, so I hope I didn't do any stupid mistakes. If you have any questions about the code, please ask.
Fiddle: http://jsfiddle.net/1q5st19f/17/
This took me forever to debug. There were a number of issues most importantly of which was that you are using a very backlevel version of prettyCheckable. However, after changing to the latest level and starting again, I have a fully working solution for you. See this jsFiddle.
I started again from the beginning but here is the code:
HTML
<fieldset>
<div class="group">
<input type="checkbox" class="parentCheckBox" data-label="Africa"/>
<div class="content">
<input type="checkbox" value="1" class="childCheckBox" data-label="Algeria" />
<br />
<input type="checkbox" value="2" class="childCheckBox" data-label="Angola" />
<br />
<input type="checkbox" value="3" class="childCheckBox" data-label="Benin" />
<br />
</div>
</div>
</fieldset>
JavaScript
$(function () {
$('input:checkbox').each(function () {
$(this).prettyCheckable();
});
$(".parentCheckBox").change(function (e) {
var checked = $(this).prop("checked");
$(".childCheckBox", $(this).closest(".group")).each(function (i, e) {
$(e).prettyCheckable(checked?"check":"uncheck");
});
});
$(".childCheckBox").change(function(e) {
var checkedCount = unCheckedCount = 0;
$(e.currentTarget).closest(".content").find(".childCheckBox").each(function(i,e2) {
if ($(e2).prop("checked")) {
checkedCount++;
} else {
unCheckedCount++;
}
});
if (unCheckedCount == 0) {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("check");
} else {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("uncheck");
}
});
});
I'll be delighted to answer any questions you may have.
The semantics of checking or unchecking all children could have an alternate solution shown in this jsFiddle. It talks to when the parent checkbox should be checked or unchecked as a function of the children.
What prettyCheckable does behind the scenes, is it hides the checkboxes and adds an a tag to the page, and updates the hidden checkboxes when the a tag is clicked. The a tag also gets a style of checked when the checkbox is checked. There appears to be a bug though, that the checked class is not added to or removed from the a tag when the state of the checkboxes is manipulated through code. Anyway, your JavaScript was correctly updating the state of the checkboxes, but prettyCheckable wasn't detecting that and failed to update its classes.
Anyway, I rewrote your script so all the logic is handled in 1 event handler, and I included a work-around for the prettyCheckable bug, but I left your HTML alone so you should only have to replace your JavaScript code. See below for a runnable example:
$('input:checkbox').prettyCheckable();
$("input:checkbox").on("change", function() {
var checkbox = $(this);
var parent = checkbox.closest("fieldset");
if (checkbox.hasClass("parentCheckBox")) {
//this is a parent, check or uncheck all children
var isChecked = checkbox.is(":checked");
//add checked attribute in the DOM and add the class for prettyCheckable on all children
parent.find("input.childCheckBox:checkbox").prop("checked", isChecked).each(function() {
if (isChecked)
$(this).next("a").addClass('checked');
else
$(this).next("a").removeClass('checked');
});
} else {
//this is a child, check or uncheck the parent
var parentCheckbox = parent.find("input.parentCheckBox:checkbox");
var isChecked = !parent.find("input.childCheckBox:checkbox").get().some(function(item) {
return !$(item).is(":checked");
});
//add the checked attribute to the dom and add the class for prettyCheckable
parentCheckbox.prop("checked", isChecked);
if (isChecked)
parentCheckbox.next("a").addClass('checked');
else
parentCheckbox.next("a").removeClass('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://qfuse.com/js/utils/prettyCheckable/prettyCheckable.js"></script>
<link href="http://arthurgouveia.com/prettyCheckable/js/prettyCheckable/dist/prettyCheckable.css" rel="stylesheet"/>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label="" /> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label="" /> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label="" /> Benin<br />
</div>
</fieldset>
I have custom filtering jQuery, the function is when the checkbox was checked it showing the rel value from the checkbox on div with class filter.
Meanwhile the div filter has default text write "Please choose".
What I need is when someone chooses the checkbox and then clicks the "Clear all" button it will clear the checked value, but at current state the default text from div filter "Please choose" does not appear again after clearing result.
Here is the Html code:
<div class="check">
<label><input type="checkbox" rel="A" name="A"/>a</label>
<label><input type="checkbox" rel="B" name="B"/>b</label>
<label><input type="checkbox" rel="C" name="C"/>c</label>
<label><input type="checkbox" rel="D" name="D"/>d</label>
<button class="clear -filter"onclick="$('input:checkbox').removeAttr('checked');
$('.results > div').show();
$('.textTrigger').html('');" type="reset" value="Clear all">Clear all</button>
</div>
<div class="filter">
<p class="textTrigger">Please choose</p>
</div>
Here is the jQuery:
$('div.check').delegate('input[type="checkbox"]', 'change', function()
{
var $lis = $('.results > div'),
$checked = $('input:checked');
var rels = [];
$checked.each(function()
{
rels.push($(this).attr('name'));
});
$('.textTrigger').html(rels.join(', '));
if ($checked.length)
{
var selector = $checked.map(function()
{
return '.' + $(this).attr('rel');
}).get().join('');
$lis.hide().filter(selector).show();
}
else
{
$lis.show();
}
});
And this is the link to fiddle http://jsfiddle.net/nucleo1985/LugPX/
Get rid of the onclick attribute on the button, it's not clean code. You're already using jQuery so I suggest you stick to that and move the JS logic away from inside the DOM element
Also use the $.fn.on function instead of delegate
And use this ..
$('button').on('click', function () {
$('input:checkbox').removeAttr('checked');
$('.results > div').show();
$('.textTrigger').html('Please choose');
});
JSFIDDLE
I'm using a CMS that hides form elements behind tags, because of some system quirks I've had to set up a checkbox that controls the radio buttons so if the checkbox is ticked the "yes" radio button is selected if not the "no" is selected. I also want the radio buttons to have option "no" checked by default but I don't have control over the line of code for the radio buttons.
I found some Javascript that does a small part of this but I want to integrate it into the jQuery that displays and hides content when the box is ticked.
Here's what I have so far:
$('#checkbox1').change(function() {
$('#content1').toggle("slow");
});
The Javascript I have is this:
function ticked(){
var ischecked = document.getElementById("checkbox").checked;
var collection = document.getElementById("hideradio").getElementsByTagName('INPUT');
if(ischecked){collection[0].checked = true;}else{collection[0].checked = false;}
}
Can you please help write a version of the Javascript but integrate with my jQuery?
Thanks,
You can try this, I assume your html as like this.
<input type="checkbox" id="checkbox1" /> Check Box
<div id="content1" >
Some Content <br />
Some Content <br />
Some Content <br />
Some Content
</div>
<div id="hideradio">
<input type="radio" name="rgroup" value="yes" /> Yes
<input type="radio" name="rgroup" value="no" /> No
</div>
JQuery
$(function(){
$('#hideradio input[type=radio][value=no]').attr('checked',true);
$('#content1').hide();
});
$('#checkbox1').on('change', function() {
$('#content1').toggle("slow");
var self = this;
if(self.checked)
$('#hideradio input[type=radio][value=yes]').attr('checked',true);
else
$('#hideradio input[type=radio][value=no]').attr('checked',true);
});
A Quick DEMO
Try this code
$(function(){
$('#checkbox1').on('click' , function() {
var isChecked = $(this).is(':checked');
if(isChecked){
$('#radio1').attr('checked' , true);
$('#content1').toggle("slow");
}
else{
$('#radio1').attr('checked' , false);
}
});
});
Check [FIDDLE]
If I don't understand correctly then let me know.
I don't know your HTML code so I provide one
<form>
<input type="checkbox" name="test_ck" id="test_ck" />
<br/>
<input type="radio" name="test_radio" id="test_radio" />
</form>
<div id="content"> A content !!! </div>
and javascript jquery
$(function(){
$("#test_ck").on("change", function(){
$("#test_radio").prop("checked", $(this).is(":checked"));
$("#content").toggle("slow");
});
});
Example -> jsfiddle
UPDATED jsfiddle
http://jsfiddle.net/6wQxw/2/
jsfiddle
$(document).on('change', '#checkbox', function() { toggle(this); });
var toggle = function(obj) {
var checked = $(obj || '#checkbox').is(':checked');
$(':radio[value=no]').prop('checked', !checked);
$(':radio[value=yes]').prop('checked', checked);
$('#content').toggle(checked);
}
toggle();
This is a pure JavaScript solution, no need to use jQuery:
<body>
<label for="a">Male</label>
<input type="radio" id="a">
<br/>
<label for="b">Female</label>
<input type="radio" id="b">
<script type="text/javascript">
var nodes = document.querySelectorAll("input[type=radio]");// get elements
var arr = Array.prototype.slice.call(nodes); // convert nodes to array for use in forEach
arr.forEach(function(obj){
obj.addEventListener("change",function(e){
arr.forEach(function(obj){
obj.checked = false;//make other radio false
});
this.checked = true;// make this radio ture
});
});
</script>
</body>
I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox