Javascript checkbox validation - disable and enable - javascript

I have a group of 3 checkboxes and I need to apply some conditions/restrictions for them.
For example, if I tick the first checkbox {{UTEP}} i'll have to disable the last one ValĂȘncias.
I have the following code:
var _restricoes = [[1, 2]];
$($('#conteudoCategorias').find('.clsF3MInput')).on('click', function (e) {
debugger
//get elems
var _id = parseInt($(this).attr("id").replace("CheckBox", ""));
for (var i = 0; i < _restricoes.length; i++) {
//get item
var _item = _restricoes[i];
//verifica se existe
var _existe = $.grep(_item, (x) => x === _id)[0];
if (_existe && CategoriasAnexosVerificaCheck($(this)) === true) {
//get other value
var _otherValue = $.grep(_item, (x) => x !== _id)[0];
//bloquear elementos
var elemsBloquear = $.grep($('#conteudoCategorias :input'), function (elem) {
return elem.getAttribute('id') !== 'CheckBox' + _id &&
elem.getAttribute('id') !== 'CheckBox' + _otherValue;
});
$(elemsBloquear).attr('disabled', true);
//desbloquear elementos
var elemsDesbBloquear = $.grep($('#conteudoCategorias :input'), function (elem) {
elem.getAttribute('id') === 'CheckBox' + _id;
elem.getAttribute('id') === 'CheckBox' + _otherValue;
});
$(elemsDesbBloquear).attr('disabled', false);
}
}
});
When I uncheck the {{UTEP}} I need to enable the checkbox ValĂȘncias again, but I can't get to it.
the array _restricoes contains the ids of the checkboxes that can be checked. If I check the first one, I can check the second one, and vice-versa. The array will have more conditions/restrictions, like this for example: _restricoes = [[1, 2], [1, 4]];
Note: The Ids of the checkboxes are dynamic, they are generated from the server, puting it simpler: the number of registrations are the checkboxes.

Your code is a weird combination between jQuery and javascript. Here is a jQuery solution how you can change the enabled property based on the checked property of another checkbox.
$('#utepId').on('change', function(){
//when #utepId is checked disable #ValenciasId
$('#ValenciasId').prop('disabled', $(this).prop('checked'));
//when #utepId is checked uncheck #ValenciasId
if($(this).prop('checked')) {
$('#ValenciasId').prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="utepId" type=checkbox /><label for="utepId">utep</label>
<input id="candbId" type=checkbox /><label for="candbId">candb</label>
<input id="ValenciasId" type=checkbox /><label for="ValenciasId">ValĂȘncias</label>

Related

Display value of multiple selected checkboxes [duplicate]

This question already has answers here:
Getting multiple values from checked checkboxes Javascript
(3 answers)
Closed 3 months ago.
I am trying to display multiple checkbox values in a separate DIV to show the results of the checkboxes to the user. But I also want to remove the value if the user de-selects the checkbox. This is the code I have so far but can only display/hide one value at a time. For example, if I click checkboxes a, b, and c, it will show all values. But If I uncheck, they will hide. Thanks
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="a"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="b"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="c"/>
<div id="acc"></div>
function selectAcc(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("acc").innerHTML = x;
}
// selecting input type checkboxes
const inputCheckBoxes = document.querySelectorAll("input[type=checkbox]");
const main = document.querySelector("#main");
// function to print in main div
const printCheckedValue = (array) => {
main.innerText = "";
array.forEach(value => {
main.innerText += value;
})
}
// to store checkboxed values
let checkedValue = [];
// looping through all inputcheckboxes and attching onchange event
Object.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {
inputCheckBoxe.onchange = (e) => {
// checking if value is checkedbox or not
if (checkedValue.includes(e.target.value)) {
// if checkeboxed than filtering array
checkedValue = checkedValue.filter(val => val != e.target.value)
printCheckedValue(checkedValue);
} else {
checkedValue.push(e.target.value);
printCheckedValue(checkedValue);
}
}
})
<input type="checkbox" name="accessory" value="a" />
<input type="checkbox" name="accessory" value="b" />
<input type="checkbox" name="accessory" value="c" />
<div id="main"></div>
Hope this works for you .
function selectAcc(cb) {
// get previous div value
var previousValue = document.getElementById("acc").getAttribute('value');
var newValue = previousValue;
//store the new clicked value
var value = cb.value;
// if the new value is checked and the value is not present in the div add it to the div string value
if (cb.checked && !previousValue.includes(value)) newValue+=value ;
// else remove the value from div string value
else previousValue = newValue.replace(value, '');
// update new value in div
document.getElementById("acc").innerHTML = newValue;
}
Try put like something this
var checked = []
function selectAcc(cb) {
if(cb.checked){
checked.push(cb.value)
} else {
var index = checked.indexOf(cb.value)
checked.splice(index, 1)
}
document.getElementById("acc").innerHTML = checked.join(' ');
}

select all method for checkboxes , should not select disabled checbox in vue.js

i have a list with checkboxes in the table , when i click select all function , it selects all checkbox including disabled ones, i neeed to exclude the disabled checkbox .
<li><a #click.prevent="selectAll" id="cardSelectAllAId">
SelectAll</a></li>
<single-checkbox class="checkbox "
inputId="card.data.id"
v-if="card.data.id"
#change="change(card.data)"
:value="card.data.selected"
:disabled="!card.data.licenseEnabled">
selectAll() {
for (let i = 0; i < this.cards.length; i += 1) {
if (this.cards[i].selected !== undefined) {
this.cards[i].selected = true;
}
},
You can try something like this in your function-
// Reset all selected first
this.cards.map((x) => x.selected = false);
// Filter and then set selected to true
this.cards
.filter((x) => x.data.licenseEnabled)
.map((x) => x.selected = true);
if(this.cards[i].selected !== undefined && this.cards[i].licenseEnabled)
this works

Unchecking of the checked checkboxes on another button click

I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}

how to get all checkboxes from one of three forms?

I have three forms, each of them has checkboxes and submit button. I need to get all checkbox names or id by clicking on the submit button in only this form.
And for other two also.
function getCheckedBoxes(item) {
var checkboxes = document.getElementsByName(item);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
console.log(checkboxes);
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
var inp = document.getElementsByName('send');
for(var i = 0; i < inp.length; i++){
inp[i].addEventListener('click', function(e) {
getCheckedBoxes("item");
e.preventDefault();
});
}
example of my checkboxes
<form>
<input id="check29" type="checkbox" name="item" value="29" />
<input class="lab-btn" type="submit" value="ADD ALL" name="send">
</form>
You can pass the form as a parameter to the function, then use querySelectorAll to get all of its inputs with the desired name.
So first, change the event handler to this:
inp[i].addEventListener('click', function(e) {
getCheckedBoxes(this.form, "item");
e.preventDefault();
});
Then the function itself to:
function getCheckedBoxes(oForm, item) {
var checkboxes = oForm.querySelectorAll('input[name="' + item + '"]');
//...
}
To select all checboxes on a page you can use:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
// And for all checkboxes in a form:
var checkboxesInForm = form.querySelectorAll("input[type=checkbox]");
See https://developer.mozilla.org/nl/docs/Web/API/Document/querySelectorAll for documentation.
Does this answer your question?

jQuery help with checking parent of checked child checkbox

I have a main row and some other rows underneath that main row like this:
[checkbox] Main heading row
[checkbox] first child row
[checkbox] second child row
When I click on the child row, it should check the parent (main) row automatically. Problem is that it doesn't check it first time I click it. I have to check the first child row first, then uncheck the first child row and then check first child row again to get the parent (main) row get checked. I want the parent row get checked as soon as any of the child rows get checked.
I am using the following code
function checkbox_click(){
var n = event.srcElement;
if(n.parentElement.id == "row"){
n = n.parentElement;
}
if(n.id == "row"){
alert("ID: 1");
n.rs = n.parentElement;
if(this.multiSelect == 0){ // single select
alert("ID: 2");
n.all[0].checked = 1;
this.selectedRows = [ n ];
if(this.lastClicked && this.lastClicked != n){
this.lastClicked.all[0].checked = 0;
this.lastClicked.style.color = "000099";
this.lastClicked.style.backgroundColor = "";
}
} else {
alert("ID: 3");
n.all[0].click();
}
if(this.parentElement == pg.procs) {
alert("ID: 4");
var terminate = false;
var counter = 0;
if(n.className == "proc") {
alert("ID: 5");
z = n.nextSibling;
while(z.id == "row" && z.className != "proc" && !terminate) {
alert("ID: 6");
z.all[0].checked = 0;
z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
counter++;
if(counter > 1000) terminate = true;
z = z.nextSibling;
}
} else {
$(".row input").change(function() {
alert("ID: 7");
var $row= $(this).closest(".row");
var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
$main_row.find(":checkbox").attr("checked", function(i,attr) {
return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
});
});
$(".proc input").change(function() {
alert("ID: 8");
$(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
});
}
If you want to check the parent checkbox when one of the child checkboxes is checked, I would suggest using a common class for the child checkboxes, and a unique id attribute for the parent checkbox (or store it as a variable).
Let's assume you have a structured HTML document that contains something like the following:
<div>
<input type="checkbox" name="ckparent" id="ckparent" />
<label for="ckparent">Parent</label>
<div>
<input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
<label for="ckchild1">Child 1</label>
</div>
<div>
<input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
<label for="ckchild2">Child 2</label>
</div>
</div>
You could then write the following jQuery code to check the parent checkbox when either of the children are checked:
$('input:checkbox.ckchild').click(function(event) {
var checked = $(this).is(':checked');
if (checked) {
$('#ckparent').attr('checked', true);
}
});
EDIT: The order in which the changed and clicked events are fired with regards to when the checked attribute is actually changed is dependent on the browser you are using -- which browsers are you targeting?

Categories