Obtaining of all values of checkboxes in JavaScript - 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

Related

Find whether all checkbox are checked within a parent div

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 )

Javascript to select all but the first checkbox on a page?

I want to be able to automatically mark all the checkboxes on a page EXCEPT the first one.
I have found a javascript snippet that selects all the checkboxes, that is currently working for that purpose, but I don't want it to select the first checkbox...
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'), function (el) {el.checked = true});
I've tried various If statements within the above snippet, all of which break the process.
Any help will be appreciated. Note:(I am implementing this as a bookmarklet.)
The callback function can take a second parameter that is the index. So add a condition that index !== 0, that is function (el, index) { if (index !== 0) { el.checked = true; } }.
Or even function (el, index) { el.checked = index !== 0; }
You could change your query selector to add :not(:first-child)
[].forEach.call(document.querySelectorAll('input[type="checkbox"]:not(:first-child)'), function (el) {el.checked = true});
Fiddle: https://jsfiddle.net/zLhhyy7m/2/
Or with jQuery:
$('input[type="checkbox"]:not(:first)').attr("checked",true);
Fiddle: https://jsfiddle.net/zLhhyy7m/1/
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; ++i) {
if (i)
checkboxes[i].checked = true;
}

How to use JavaScript to Require a Ratio of Completed Fields in a Form

I'm looking for a way to use JavaScript to require a specific ratio of fields in a form to be complete. So if I have six fields and the user has to complete any 2/6 to submit. If not then they receive an error. (The form will actually have a few different groups like this in it, so I have to be able to identify specific fields for the ratio.)
After some more research I've found something close, and realize I can count the number of a class. How would I change this to say if number of checked boxes is greater than or equal to 2, return true?
document.getElementById("test").onclick = function() {
isCountCheck("Check something");
};
function isCountCheck(helperMsg) {
var i, len, inputs = document.form1.getElementsByClassName("checkbox");
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) return true;
}
alert(helperMsg);
return false;
}
UPDATE:
My final jQuery ended up like this.
function isCountCheck(){
if($("input[class=crit1]:checked").length >= 4)
return false;
alert("Check a box");
return true;
}
Using jQuery
var numberOfInputsCompleted = 0;
var allInputs = $(":input"); // returns all input fields on the document
var numberOfInputs = allInputs.length
allInputs.each(function () {
if($(this).val() != '') {
numberOfInputsCompleted = numberOfInputsCompleted + 1;
}
});
numberOfInputsCompleted would give fields completed and numberOfInputs would total number of input fields on the form. Hope this helps
The first thing that comes to my mind: create a function that counts filled fields and returns true if the number of filled fields is enough (false otherwise). Then add it to the form as an "onsubmit" function. When the submit button is clicked the function is executed and, depending on what the function returns (true or false), the form is submitted or not.
More info about javascript form validation: http://www.w3schools.com/js/js_form_validation.asp

How to go over all inputs that have a custom attribute

I have a form with checkboxes.
All of the checkboxes have an attribute called att, which contains several numbers that are separated by commas.
I'd like to create a function that gets a number, goes over all the checkboxes and checks all the checkboxes that their att attribute contains that number.
Can please someone point me at the right direction?
Using jQuery you can do something like
function myfunc(num)
{
$(":checkbox[att!='']").each(function()
{
var i, l, values = $(this).attr("att").split(",");
for (i = 0, l = values.length; i < l; ++i)
{
if (values[i] == num)
{
$(this).attr("checked", "checked");
break;
}
}
});
}
With JQuery you would use the attribute-contains selector to get all elements where an attribute contains a certain value.
$('input[att*="100"]').val('input has 100 in it!');
This loops over all input elements and gives you an array containing the values of att (split using the comma), so I'd add some logic to pick out only checkboxes:
for (var i = 0; i < document.getElementsByTagName('input'); i++)
{
var att_array = document.getElementsByTagName('input')[i].getAttribute('att').split(',');
}
This will get you all inputs with the attribute ATTR and then alerts the val of each of those. You can, of course, do whatever you want with the val when you have it.
$("input[ATTR]").each(function(){
alert($(this).attr("ATTR"))
})
If you want to limit this to checkboxes, change the selector as is shown below
$(":checkbox[ATTR]").each(function(){
alert($(this).attr("ATTR"))
})

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