Pass checkbox value IF the checkbox is checked - javascript

I have a list of checkboxes that looks like this:
<div class="checkbox">
<label><input type="checkbox" value="west" name="west" id="west" checked="{{isChecked}}">West</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="airport" id="airport" value="airport">Airport</label>
</div>
<div class="checkbox">
<label><input type="checkbox" checked="{{isChecked}}" name="north" id="north" value="north">North</label>
</div>
I have managed to pass the status of each checkbox as a boolean to the collection like this:
var eventLocation = [
event.target.west.checked,
event.target.airport.checked,
]
However, I would like to pass only the value of the checked checkboxes. I know I can pass the value of the checkboxes with event.target.west.value, but to get only the checked ones I would have to write many conditionals, which would not scale well. Is there a better way of doing this?
Thank you!

You can quickly gather all checked checkboxes with:
var checked = $("input:checked");
This will return an array that you can loop over to get the id, value, or name.
checked.forEach(function(c){
console.log('input id: '+c.id+' name: '+c.name+' value: '+c.val+' is checked!');
});

Related

How to make an unchecked checkbox value 0 and checked value of 1?

I'm making a simple registration form with a declaration asking if the user has read the terms and conditions but when I console log the value of the checkbox it doesn't change depending on if it's checked or not. How do I do this? I've seen other people ask the question but they're using JS libraries like jQuery which I'm not using so how do you differentiate the value from checked and unchecked just using basic JS and HTML
<div class="item">
<input type="checkbox" id="checkbox" value="1">
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>
This is the div containing the checkbox.
You can add an event handler onClick in order to achieve this:
function handleClick(cb) {
cb.value = cb.checked ? 1 : 0;
console.log(cb.value);
}
<div class="item">
<input type="checkbox" id="checkbox" value="1" onclick='handleClick(this);'>
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>
You can use the .checked method:
var checkBox = document.getElementById("checkbox");
if(checkbox.checked){
console.log("checked");
}
else{
console.log("unchecked");
}
You need to test the .checked property. To convert it to an integer, you can use the bitwise OR operator.
document.getElementById('checkbox').addEventListener('change', function(e){
let checked = this.checked;
console.log(checked);
console.log(checked | 0);
});
<div class="item">
<input type="checkbox" id="checkbox">
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>

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

Two checkboxes acting as one

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.

jQuery lookup from databound checklist

My MSCRM 2015 online solution uses a 3rd party tool to build a checkbox list from N:N dynamically and this is then published in another Iframe, I was wandering if I could use jQuery to test if any of these checkboxes are checked in JavaScript
Problem though if you look at the html these inputs don't have id's or names I can use to reference them with something like ...
var checkboxValues = [];
$('input[name=checboxset_ava_incident_ava_affectedcountry]:checked').map(function() {
checkboxValues.push($(this).val());
Here is an example of how the html get build:
hope the sizing is ok to read But what I want you to see is the <input> tag's properties:
<input type="checkbox" data-bind="id: Id, checked: Value, title: Name, enable: $parent.GetIsEnabled()">
If you want to find selected checkboxes, radio buttons or select elements, look at the jQuery :checked selector, as in
$(':checked')...
If you want checkboxes, use the type attribute in your selector, as in
$('input[type=checkbox]')...
or combine them, to find only checked checkboxes (i.e., to ensure that you don't pick up any radio buttons or select elements):
$('input[type=checkbox]:checked')...
DEMO
var findChecked = function() {
var checked_values = [];
var $checkedBoxes = $('input[type=checkbox]:checked');
console.log('$checkedBoxes', $checkedBoxes.length);
$checkedBoxes.each(function(i, e) {
checked_values.push($(e).val());
});
alert(checked_values);
};
$('button').click(findChecked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" checked value="1" /> 1</label>
<label><input type="checkbox" value="2" /> 2</label>
<label><input type="checkbox" value="3" /> 3</label>
<button>See checked</button>

checking if multiple checkboxes are checked using custom attribute in jquery

I have multiple groups of checkboxes like these:
<input type="checkbox" class="correction_check" product_id="3" defect_col="Qty">
<input type="checkbox" class="correction_check" product_id="3" defect_col="Exp">
<input type="checkbox" class="correction_check" product_id="3" defect_col="Bat">
<input type="checkbox" class="correction_check" product_id="4" defect_col="Qty">
<input type="checkbox" class="correction_check" product_id="4" defect_col="Bat">
A group of checkboxes is differentiated by product_id.
Can I do something like this?
$('.correction_check').click(function(){
//check if all other check boxes having same product_id as $(this) are checked and do some action
});
You can test if all other checkboxes with same product_id are checked like this :
$('.correction_check').click(function(){
var otherAreChecked = $('.correction_check[product_id='+$(this).attr('product_id')+']')
.not(this).not(':checked').length===0;
// do action
});
The idea is to count the ones that are not checked : this count should be 0.
Demonstration
Note that if you want to know if all check boxes with same product id are checked (not just the "other" ones), you just have to remove .not(this) from my code
Try this:
$(".correction_check").change(function(){
var id = $(this).attr("product_id");
$(".correction_check[product_id='"+id+"']:checked").each(function(){
//do action
});
});

Categories