Disable every non checked checkbox - javascript

I have a bunch of forms with a checkbox in each of them and when a condition is met i want to disable every checkbox that is NOT checked.
I've tried doing this but with no luck
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]:not(:checked)').disabled = true;
}
I would preferably only use vanilla javascript.

querySelectorAll returns a NodeList object, you have to use that object to iterate through the elements and disable them.
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach((element) => {
element.disabled = true;
});
}

You can use something like this:
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]').forEach(i => i.disabled = true);
}
Edit: I was too slow. Already suggested by #Gunther: https://stackoverflow.com/a/65692054/4261813

You will need to loop through the results of querySelectorAll.
if (updateShowcasedProducts.length == 12) {
els = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
for (const el of els) {
el.disabled = true;
}
}

You can first use a class for all those inputs what are checkboxes. And then use checked property:
let checkBoxes = document.getElementsByClassName("checkbox");
checkBoxes.forEach(checkBox)=>{
if(!checkBox.checked){
checkBox.disabled=true;
};
});

Related

How to set checkbox priority?

A common checkbox is available here. .bucret
If these two ids are selected, the value will be printed. .bucret + .engelli
$(".engelli, .bucret").click(function () {
let isBox2Checked = $('.engelli input').is(':checked');
let isBox3Checked = $('.bucret input').is(':checked');
if (isBox2Checked && isBox3Checked) {
$('#textbox2').attr('value', '1.800,00');
} else {
$('#textbox2').attr('value', '');
}
If the .bucret checkbox alone is checked, this value is written.
$('.bucret').change(function() {
if ($('.bucret input').is(':checked')) {
$('#textbox2').attr('value', '1.950,08');
} else {
$('#textbox2').attr('value', '');
}
});
});
Unfortunately it doesn't work that way. First, I select .engelli id, then the .bucret id is selected and the value is written as 1.950.08.
Your issue occurs because you have two different event listeners that do their own thing. The last one firing is the one that wins. Why not combine your logic in one listener?
I'd advice to use the change event instead of click. Write an extra else if statement to see if only .bucret is checked or not.
$(".engelli, .bucret").on('change', function () {
let isBox2Checked = $('.engelli input').is(':checked');
let isBox3Checked = $('.bucret input').is(':checked');
if (isBox2Checked && isBox3Checked) {
$('#textbox2').attr('value', '1.800,00');
} else if (isBox3Checked) {
$('#textbox2').attr('value', '1.950,08');
} else {
$('#textbox2').attr('value', '');
}
});

validating checkbox limit javascript

var cbx = document.getElementById('ModelFilter').getElementsByTagName('input');
var ArrCB_l=cbx.length;
while(ArrCB_l--){
var CB=ArrCB[ArrCB_l];
CB.checked()==True;
return 1
}
return 0
Can anyone tell me what is wrong with this? I know the first line is the correct input as I am using it elsewhere for the same checkboxes, however this won't work? I am trying to make sure there is at least one checkbox checked. This function is called with an onsubmit event.
while(ArrCB_1) {
if(cbx[--ArrCB_1].checked) {
return true;
}
}
return false;
.checked() should be just .checked
while(ArrCB_l--){
if (cbx[ArrCB_l].checked) {
return true;
}
}
return false;
your collection is cbx and not ArrCB, and checked is not a method but it's an attribute/property of the element
document.getElementById('ModelFilter').getElementsByTagName('input');
this code returns all inputs(text,button,radio etc)
use
document.getElementById('ModelFilter').getElementsByTagName("input")[ArrCB_l].type == "checkbox"

Check if DOM Element is a checkbox

How can I check if a given DOM element is a a checkbox.
Scenario:
I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.
Using only vanilla javascript you could do
if (el.type && el.type === 'checkbox') {
...
}
or even shorter
if ((el || {}).type === 'checkbox') {
...
}
or in modern browsers you could use matches()
if (el.matches('[type="checkbox"]') {
...
}
If you're using jQuery, you can use the :checkbox pseudo-class selector along with is method:
if($("#that-particular-input").is(":checkbox")) {
}
Checks anything
function isCheckbox (element) {
return element instanceof HTMLInputElement
&& element.getAttribute('type') == 'checkbox'
}
if( $(element)[0].type == "checkbox" ) {
}
OR
if( $(element).is(':checkbox') ) {
}
Take a look at the checkbox selector.
var checkboxes = $("form input:checkbox");
You can tell what type an input is like this:
if ($(".your-input").is(":text"))
{
// Textbox
}
else if ($(".your-input").is(":checkbox"))
{
// Checkbox
}
if (<DOMNode>.type === "checkbox") {
// ...
}
Try this;
$(element).is(':checkbox');
here element is selector to your element
if( $(element).is(':checkbox') ) {
// do something
}
jQuery is():
if ($el.is(':checkbox')) { ... }
You can use the pseudo-selector :checkbox with a call to jQuery's is function:
$('#myinput').is(':checkbox')
You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name.
e.g. "chkMyCheckbox"

Determine if all checkboxes within jQuery object are checked, return as boolean

Hey all. I've been been trying to figure this out for a while now.
I create a jQuery object of checkboxes and store it in a variable:
$group1 = $('#checkbox1,#checkbox2,#checkbox3,#checkbox4');
The user cannot continue unless all checkboxes in that group are checked.
I've been using an if statement combined with .is(':checked') to find a boolean value:
if( $group1.is(':checked') ){
//continue is OK
}
...but .is(':checked') will return TRUE if any checkboxes are checked within the group. Essentially, .is(':checked') performs an OR operation on the selected elements in $group1. I'm looking for an AND operation, so all selected elements must be checked to return TRUE. Is there a jQuery function that does this, or another workaround?
#Adam is off just a bit
if( $group1.filter(':not(:checked)').length === 0){
//continue is OK
}
Corrected:
You could filter to get only the elements that are not checked, and then check to see if any are any elements still in the collection, if there are not than all the elements in the group are checked:
if( $group1.filter(':not(:checked)').length === 0){
//continue is OK
}
I think you need something like:
$(document).ready(function(){
var checked = true;
$('input:checkbox').each(function(){
if(checked){
checked = $(this).is(':checked');
}
});
});
This should set checked = false if any of them are unchecked.
I would suggest that you give your checkboxes a a class then
var len = $('.check_needed').length;
var chk = $('.check_needed:checked').length;
if (len == check){
//carry on
}else{
// go home
}
You can use also
$(function(){
// add multiple select / deselect functionality
$("#selec_all_chk").click(function () {
$('.chk_class').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// else uncheck
$(".chk_class").click(function(){
if($(".chk_class").length == $(".chk_class:checked").length) {
$("#selec_all_chk").attr("checked", "checked");
} else {
$("#selec_all_chk").removeAttr("checked");
}
});
});

jQuery - Find any input with a given class that has no value

I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});

Categories