Find whether all checkbox are checked within a parent div - javascript

I am trying to get the state of two input checkboxes within a div element. I need to set a flag variable to true only if both the checkboxes are checked. If any of the input checkbox is unchecked , then it should be set to false.
I tried this using for loop using the below code
var oParNode = oNode.ParentNode;
if (null != oParNode) {
for (var i = 0; i < oNode.ParentNode.Nodes.length; i++) {
if (oNode.ParentNode.Nodes[i].Checked) {
checked = true;
}
else {
checked = false;
}
}
}
In this code , Nodes[i] returns the input element. When I check the first checkbox first and the second one next this loop works fine but when I check the second one first , the checked variable is set to true based on the second checkbox value which is executed at last.
Expected: I need to return "checked" to be true only if both checkboxes are checked .
Can some one suggest me on this.

You can use Array#some() method, to check if there's an unchecked one:
var checked = oNode.ParentNode.Nodes.some(check => !check.checked)

Seems for second node it is overriding the value. If you know there are two checkboxes you can directly check it like this.
if (oNode.ParentNode.Nodes[0].Checked && oNode.ParentNode.Nodes[1].Checked) {
checked = true;
} else {
checked = false;
}

Instead of finding all checked, find unchecked instead since this is what you are looking for.
var checked = true;
for (var i = 0; i < oNode.ParentNode.Nodes.length; i++) {
if (!oNode.ParentNode.Nodes[i].Checked) {
checked = false;
break;
}
}

You need to break your loop in case any of checkbox is not checked
var oParNode = oNode.ParentNode;
if (null != oParNode) {
for (var i = 0; i < oNode.ParentNode.Nodes.length; i++) {
if (oNode.ParentNode.Nodes[i].Checked) {
checked = true;
} else {
checked = false;
break;
}
}
}
You can simply every method of array instead of loop
let checkedAll = oNode.ParentNode.Nodes.every(element => element.checked )

Related

Cannot return a True or Force value out of a variable within an if statement in Angular

I have the following checkbox who is calling a function on launch to get checked based on a value that comes in from an api (cat.term_id)
<input ng-checked="ifCatExcluded(cat.term_id)">
The function works as follows: The first bit sets the checkbox value to true and gets an array which i need to cross check the id.
$scope.ifCatExcluded = function(sent_id){
var doesNotExist = true;
arraytosearch = JSON.parse(localStorage.getItem("categoryListMem"));
The second bit creates an empty array and adds the cat.term_id to this new array to avoid re running this id later.
if($scope.tempArray == undefined || $scope.tempArray.indexOf(undefined) > 0) {
$scope.tempArray = [];
}
if ($scope.tempArray.indexOf(sent_id) < 0) {
$scope.tempArray.push(sent_id);
console.log($scope.tempArray);
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i]['id'] == sent_id) {
doesNotExist = false;
console.log(sent_id + " IS EXCLUDED");
}
}
}
Then the last part returns the value for the checkbox and here is the problem. I cannot get a return of true or false from the doesNotExist variable. I noticed that when I take
for (var i = 0; i < arraytosearch.length; i++) {" ecc...
out of the if statement everything works...
return doesNotExist;
console.log(doesNotExist);
};
Any help is much appreciated.

GridView Validation is not working properly in JavaScript

I want to validate on button click that at least one of the rows must be edited and updated in JavaScript.
So I wrote the below code for validation
function checkGridValidate() {
var StrPriError = "";
var grdCount = GrdProspective1.Rows.length;
for (var i = 0; i < grdCount; i++) {
if (GrdProspective1.Rows[0].Cells[5].Value == "" || GrdProspective1.Rows[0].Cells[7].Value == "") {
StrPriError += "Kindly edit atleast one row \n";
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
}
}
What happening here is, when I update the first row and submit it is not giving any alert that's perfect, but when I update the second row it still asks me Kindly edit at least one row.
I don't know what's going wrong here.
Have a look the js fiddle for the same
Currently, the validation is limited to only check the top row for two reasons:
.Rows[0] will always inspect the top row, despite the for loop.
This should make use of i as it increments through the collection:
if (GrdProspective1.Rows[i].Cells[5].Value == "" ||
The last if..else, by returning in either case, will interrupt the loop. The return statements here have a similar effect to break statements, with regards to the loop.
So, unless you want the loop to be interrupted, they should be moved out the loop:
for (var i = 0; i < grdCount; i++) {
if (...) {
// ...
}
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
Though, fixing those should reveal a different issue โ€“ the function is checking that every row has been edited rather than one-or-more.
If, for example, there are 5 rows and you fill in both fields in 2 of the rows, the remaining 3 rows will match the condition and append the error message.
Inverting the condition, so you're searching for a row that's filled in and remembering whether you have, should resolve this.
function checkGridValidate() {
// assume invalid until found otherwise
var anyEdited = false;
var grdCount = GrdProspective1.Rows.length;
for (var i = 0; i < grdCount; i++) {
var cells = GrdProspective1.Rows[i].Cells;
// verify that both fields were given a value
if (cells[5].Value !== "" && cells[7].Value !== "") {
anyEdited = true; // remember that you've found an edited row
break; // and, no need to keep looking for more
}
}
// alert only if no rows were filled out
if (!anyEdited) {
alert("Kindly edit at least one row.");
}
return anyEdited;
}

HTML 5 toggling the contenteditable attribute with javascript

enter code hereI am trying to make something editable online with a function like this
function toggle_editable (div, cssclass) {
var classToEdit = document.getElementsByClassName(cssclass)
for (i = 0;classToEdit.length; i++) {
if (classToEdit[i].contentEditable == false) {
classToEdit[i].contentEditable = true ;
}
if (classToEdit[i].contentEditable == true) {
classToEdit[i].contentEditable = false ;
}
}
}
classToEdit is a collection of HTML elements with the same class name or whatever document.getElementsByClassName(cssclass) returns
when going through the debugger it jumps over the line
classToEdit[i].contentEditable == true
as well as over the line
classToEdit[i].contentEditable == true
and does not execute the code in the braces following the if statements
this works however - meaning it sets the contenteditable property without hesitation
classToEdit.contenteditable = true;
as well as this
classToEdit.contenteditable = false;
(well obviously)
also this seemed to have no effect
classToEdit.contenteditable = !classToEdit.contenteditable
ideas anyone?
ps why is the loop
You've created an infinite loop here:
for (i = 0;classToEdit.length; i++) {
Should be:
for (var i = 0; i < classToEdit.length; i++) {
But, if you say classToEdit.contenteditable = true "works", you've to define "not working/is working" since the snippet doesn't definitely do what you expect it to do, if classToEdit is a HTMLCollection.
It looks like you'd want to toggle contentEditable values, you can do it like this:
for (var i = 0; i < classToEdit.length; i++) {
if (classToEdit[i].contentEditable == false) {
classToEdit[i].contentEditable = true ;
} else { // Notice else here, no need for another check
classToEdit[i].contentEditable = false;
}
}
Or simply without ifs in the loop:
classToEdit[i].contentEditable = !classToEdit[i].contentEditable;
Your current code will switch the value back to it's original in a case the value was false.
HTMLElement.contentEditable returns a string and not a boolean.
Hence, what you want to identify the state of your editable field is:
// Incorrect
classToEdit[i].contentEditable == true
// Coorect
classToEdit[i].contentEditable === 'true'
What's even better if you want to know the state of your fields is to use HTMLElement.isContentEditable
which returns a boolean:
classToEdit[i].contentEditable = !element.isContentEditable
Another way to refactor the above:
function toggleContentEdit() {
var editableFields = document.getElementsByClassName('editable');
[].forEach.call(editableFields, function(field){
var isEditable = field.isContentEditable;
field.setAttribute('contenteditable', !isEditable);
});
};
JSFiddle: http://jsfiddle.net/6qz3aotv/

Obtaining of all values of checkboxes in JavaScript

I have a html-form with checkboxes.
It is required that has been checked by at least one any checkbox.
How do I use JavaScript to get the values โ€‹โ€‹of all checkboxes, and if there is not one checked among checkboxes then show alert with message?
Since you have tagged this post with jquery here is a jQuery option.
This function selects all the checkboxes on the page, narrows it down to only the checked ones, then get's the size of the jQuery object.
if ($('input:checkbox').prop('checked').size() == 0)
{
alert('no checkboxes were checked');
}
Hope that helps. :)
// utility function
function toArray(obj) {
var arr = [];
for (var i = 0, len = obj.length; i < len; i++) {
arr[i] = obj[i];
}
return arr;
}
// get the form
var someForm = ...;
// get all elements and check whether any has type "checkbox" and is checked.
var checked = toArray(someForm.elements).some(function (el) {
return el.type === "checkbox" && el.checked;
});
if (!checked) {
alert("please check a box");
}
For browser support use the DOM-shim and the ES5-shim

How do I change the name of multiple selected html values?

I have about 20 check boxes. When the user selects these and then uses an alternate submit button, I need to change the name of the name/value pair, for the selected inputs.
Why does this function only change the name of every other selected input?
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].checked == true)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
The output:
newname
'105'
OGname
'106'
newname
'107'
OGname
'108'
newname
'109'
OGname
'110'
By renaming the first element of the list you have reduced the length of the list by one and deleted the first element. Next time through the loop the previous second element is now the first, and the second is the old third.
I'm no javascript expert, but something along the lines of this might work.
function sub_d()
{
i=0;
while (document.checks.OGname.length > i)
{
if (document.checks.OGname[i].checked="true")
{
document.checks.OGname[i].name="newname";
}else{
i++;
}
}
document.checks.submit();
}
As I said, no warranty or guarantee.
Would be great if you provide a more detailed description of your scenario, but I wish that my answer be useful.
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].type == 'CHECKBOX')
if (document.checks.OGname[i].checked)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
I usually manage dom collections in this way: (I don't know if is the best way)
function sub_d()
{
var theInputs = document.checks.getElementsByTagName('input');
for (var i = 0; i < theInputs.length; i++)
{
if (theInputs[i].type == 'CHECKBOX')
if (theInputs[i].checked)
{
theInputs[i].name="newname";
}
}
document.checks.submit();
}
With your guys help I came up with this, seems to work well. Let me know if it can be improved for others to use...
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].checked == true)
{
document.checks.OGname[i].name="newname"; //change name of input data so we know it is for other function
//By renaming the first element of the list, we have reduced the length of the list by one
//and deleted the first element. This is why we need to keep i at it's current position after a name change.
i=i-1;
}
}
//When there is only one check box left it's propert length becomes undefined.
//We will need this statement for the last undefined check box not covered in the for loop
//We can no longer index user[0]
document.checks.OGname.name="newname";
document.checks.submit();//submit these checked values to the .exe
}

Categories