Two checkboxes acting as one - javascript

I have two checkboxes on a page and I want them to act as only one. For example, I select one, and the other is selected automatically, and vice-versa.
I've managed to select both of them at once, but I can't seem to figure out a way to deselect them at once.
And what's bothering me the most, is that it's probably a super simple line of code that I'm simply not remembering.
Is there a way to do this?

Is this what you're looking for?
$(".test").change(function () {
$(".test").attr("checked", this.checked);
});
<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />

Here is a solution in pure javascript:
// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');
// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
// Then, add `change` event on each checkbox
checkbox.addEventListener('change', function(event) {
// When the change event fire,
// Loop through the checkboxes list and update the value
checkboxes.forEach(function (checkbox) {
checkbox.checked = event.target.checked;
});
});
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>

$(document).ready(function() {
$('#check_one').change(function() {
$('#check_two').prop('checked', $('#check_one').prop('checked'));
});
$('#check_two').change(function() {
$('#check_one').prop('checked', $('#check_two').prop('checked'));
});
});
<form>
<label>Simple checkbox</label>
<input type="checkbox" id="check_one" />
<label>Complicated checkbox</label>
<input type="checkbox" id="check_two" />
</form>
Assuming you have two checkboxes named differently but working in concert, this code would work

html:
<input type="checkbox" id="1" class="handleAsOne">
<input type="checkbox" id="2" class="handleAsOne">
javascript (jquery):
$('.handleAsOne').on('change'){
$('.handleAsOne').prop('checked', false);
$(this).prop('checked', true);
}
if i understood your question correctly you are looking for something like this.

Related

How can I disable all checkboxes on webpage at once?

I have several sets of checkboxes on a webpage. I want to uncheck them all with javascript. Right now, I do it by looking for the names of each set and unchecking them with FOR loops like this...
for (i=0;i<document.getElementsByName("myboxes").length;i++) {
document.getElementsByName("myboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("moreboxes").length;i++) {
document.getElementsByName("moreboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("evenmoreboxes").length;i++) {
document.getElementsByName("evenmoreboxes")[i].checked=false;}
I'm looking for a way to target them all with one loop. I could do getElementsByTagName('input') to target all INPUTS, but that's a problem because I have some radio inputs that I don't want to uncheck. Is there a way to target all checkbox inputs?
Thanks for the suggestions. I just thought of something. Each NAME I use has the word "boxes" in it, myboxes, moreboxes, evenmoreboxes. Is there a way to target the word "boxes" in in the name, like a wildcard, something like document.getElementsByName("*boxes") that way if I add a set of checkboxes at some point that I don't want to uncheck I can simply name them differently.
You can select all checked checkboxes and reset their state:
function uncheckAll() {
document.querySelectorAll('input[name$="boxes"]:checked')
.forEach(checkbox => checkbox.checked = false);
}
<input type="checkbox"/>
<input type="checkbox" name="a_boxes" checked/>
<input type="checkbox"/>
<input type="checkbox" name="b_boxes" checked/>
<input type="checkbox" name="c_boxes" checked/>
<button onclick="uncheckAll()">Reset</button>
you can use document.querySelectorAll('input[type="checkbox"]'); to get a list of them all. then run your loop
My proposal is:
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => echecked=false);
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => e.checked=false);
<input type="checkbox" name="myboxes" value="1" checked>1<br>
<input type="checkbox" name="moreboxes" value="2" checked>2<br>
<input type="checkbox" name="evenmoreboxes" value="3" checked>3<br>
As suggested by #imjared, you can use querySelectorAll, but you will have to iterate over it:
querySelectorAll('input[type="checkbox"]').forEach(c => c.checked = false);
Here is the doc for querySelectorAll

jquery syntax for .on("change","input[name^=

Project Focus
Toggle Checkbox(es)
Special Requirement
Need to bind the new(dynamically) added div.id container that holds these checkboxes. Note: this div.id has been dynamically generated (client-side).
Status
My Working Fiddle successfully toggles between 1(one) or 0(none) checkboxes.
The HTML
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>
Working Script
var checkboxes;
checkboxes = $("input[name^=iso_01]").change(function (e) {
checkboxes.not(this).prop("checked", false);
}
});
Desired Result
I'm having trouble with syntax for updating .click() to .on("click","input..." see Bound Fiddle
Updated Script
var checkboxes;
checkboxes = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
checkboxes.not(this).prop("checked", false);
}
});
Your issue is,
checkboxes = $("#bind_id").on
is not doing what you think it is doing. It is not storing all the matched nodes.
Try this instead:
In the callback, change
checkboxes.not(..)
to
$('input[name^=iso_01]').not(this).prop("checked", false);
Working fiddle
Or if they are loaded dynamically, you can use $('#bind_id').find('input[name^=iso_01]')
This is not what checkboxes are for. You should be using radio buttons:
<input type="radio" name="example" value="1" id="1">
<label for="1">one</label>
<input type="radio" name="example" value="2" id="2">
<label for="2">two</label>
The problem is checkboxes is the #bind_id element, not the checkboxes. You would need to find the children from that element, to get the child checkbox elements.
Working Example:
var wrapper;
wrapper = $("#bind_id").on("change", "input[name^=iso_01]", function (e) {
if (this.checked) {
wrapper.find("input[name^=iso_01]").not(this).prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="bind_id">
<input type="checkbox" name="iso_01[]" class="setTitlePre1" value="L/R" />
<label for name "iso_01" class="isoVar1">No.1</label>
<input type="checkbox" name="iso_01[]" class="setTitlePre2" value="Alt" />
<label for name "iso_01" class="isoVar2">No.2</label>
</div>

Need a way to integrate an Invert function(Check All/Uncheck All) through radio buttons - for the Checkbox group

Am relatively new to what I am doing here. I am just putting together stuff with what I find here and other open resources.
The problem I am having is - With the current setup a person can choose a radio button and check a couple boxes and goto the other radio button option and choose boxes under that. I am trying to get the Checkboxes to be All Checked when someone selects the radion option and UncheckALL when the person chooses another option on the radio button group.
So if I select option 'a' under 'GENERAL' and then goto 'DETAILED' - 'a' should be unchecked.
Heres the code I am using in JFiddle
HTML:
<div id="RadioWidget">
<label><input type="radio" name="chkboxs" value="General" />General Clean</label>
<label><input type="radio" name="chkboxs" value="Detailed" />Detailed Clean</label>
<label><input type="radio" name="chkboxs" value="Commercial" />Commercial Clean</label>
</div>
<div id="General" class="desc">
<p class="maintextBlue">General
<label><input type="checkbox" name="GeneralOptn[]" value="a" />a</label>
<label><input type="checkbox" name="GeneralOptn[]" value="b" />b</label>
</p>
</div>
<div id="Detailed" class="desc">
<p class="maintextBlue">Detailed
<label><input type="checkbox" name="DetailedOptn[]" value="a" />a</label>
<label><input type="checkbox" name="DetailedOptn[]" value="b" />b</label>
</p>
</div>
<div id="Commercial" class="desc">
<p class="maintextBlue">Commercial
<label><input type="checkbox" name="CommercialOptn[]" value="a" />a</label>
<label><input type="checkbox" name="CommercialOptn[]" value="b" />b</label>
</p>
</div>
Jscript:
$(document).ready(function() {
$("div.desc").hide();
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#" + test).show();
});
});
This was a piece of script I found that inverts the checkbox state. But not sure how to integrate it to the radio button. this snippet was working off a onClick() fn for a button.
$("A[href='#invert_selection']").click( function() {
$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each( function() {
$(this).attr('checked', !$(this).attr('checked'));
});
return false;
});
Any help is much appreciated...
this requires you to add IDS to your input fields... but it would work.
If you want to control multiple input fields you can always uses classes to..
jQuery("#generalA").click(function(){
if(jQuery(this).is(':checked')){
// is checked do some stuff if you want
}else{
// is mot checked uncheck the checkbox with an ID of #detailedA
jQuery('#detailedA').prop('checked', false);
}
return false;
});
The above response by AndrewMac helped.
I just had to figure out a way it helped my existing setup.
Below is the small addition I did to get the desired setup - this way it actually disables all the unnecessary inputs thereby eliminated from the final send out of the form.
$(document).ready(function() {
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("#" + test).show().find('input, textarea').prop('disabled', false);;
});
});
I have also updated the same on my fiddle page. Fiddle
Thanks for the help AndrewMac - Sorry for the long time to post this response/answer.

CheckAll/UncheckAll checkbox with jQuery

I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')

Uncheck all other checkboxes

I need to clear all other checkboxes when a user clicks a checkbox. Pretty much the same behavior as a radio button. User clicks checkbox 'A' and checkboxes 'B' and 'C' are both unchecked. I am using jquery but I can't figure out how to accomplish this. Any ideas?
Here are how the checkboxes are set u:
<div class="sales_block_one">
<span class="sales_box_option_set"><input type="checkbox" value="1" id="exopt10i11553501716" name="optset[0][id]" /><label for="exopt10i11553501716">Test + £100.00</label></span>
<span class="sales_box_option_set"><input type="checkbox" value="2" id="exopt11i21553501716" name="optset[1][id]" /><label for="exopt11i21553501716">Test + £ 200.00</label></span>
<span class="sales_box_option_set"><input type="checkbox" value="3" id="exopt12i31553501716" name="optset[2][id]" /><label for="exopt12i31553501716">Test 3 + £400.00</label></span>
</div>
if all the checkboxes are siblings, it's just like this,
$(':checkbox').change(function(){
if (this.checked) {
$(this).siblings(':checkbox').attr('checked',false);
}
});
crazy demo
Well, if you really want to copy the behavior of the radio button, simple as this,
$(':checkbox').change(function(){
this.checked = true;
$(this).siblings(':checkbox').attr('checked',false);
});
crazy demo
siblings is when the elements has one same parent/container.
sample
<div>
<input type="checkbox" /><label>A</label>
<input type="checkbox" /><label>B</label>
<input type="checkbox" /><label>C</label>
<input type="checkbox" />​<label>D</label>
</div>
in that, <input>s and <label>s are siblings.
In your case, which it's not siblings, you can do it this way,
$('.sales_block_one :checkbox').change(function() {
var $self = this; // save the current object - checkbox that was clicked.
$self.checked = true; // make the clicked checkbox checked no matter what.
$($self).closest('span') // find the closest parent span...
.siblings('span.sales_box_option_set') // get the siblings of the span
.find(':checkbox').attr('checked',false); // then find the checbox inside each span and then uncheck it.
});​
crazy demo
more about traversing
$("#checkboxA").click(function() {
var checkedStatus = this.checked;
$("#checkboxB_And_C_Selector").each(function() {
this.checked = !checkedStatus;
});
});

Categories