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

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;
}

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 )

setcellvalue not working on all pages in JQWidget grid

I am using a JQWidget grid with paging to display table data, and I am replacing the values in one column with a string. This works fine for the initial page, but when I open the next page in the table I no longer get the string replacements, only the original value.
My home page uses this code, which works as expected ('A' and 'W' are replaced by 'newString' and 'newString2' in the table):
$("#jqxgrid").bind("bindingcomplete", function (event) {
var numrows = $("#jqxgrid").jqxGrid('getrows');
for (i = 0; i < numrows.length; i++) {
var value = $("#jqxgrid").jqxGrid('getcellvalue', i, 'column');
if (value == 'W') {
$("#jqxgrid").jqxGrid('setcellvalue', i, 'column', 'newString');
}
else if (value == 'A') {
$("#jqxgrid").jqxGrid('setcellvalue', i, 'column', 'newString2');
}
});
I tried a few ideas for the new page, such as placing the above binding function into a loop based on the number of pages:
var paginginfo = $("#jqxgrid").jqxGrid('getpaginginformation');
for (i = 0; i < paginginfo.pagescount; i++) { ...
and I also tried putting the binding function inside another function tied to the page change event:
$("#jqxgrid").bind("pagechanged", function (event) {
$("#jqxgrid").bind("bindingcomplete", function (event) { ...
but neither of these worked.
Perhaps 'numrows' is limiting setcellvalue to the first page?
Thanks //
The "binding function" is not a function, it is an event which is raised usually once the binding is completed, to in general you tried to bind to an event within another event and that normally results in nothing. You loop code - for (i = 0; i < numrows.length; i++) {... would probably not work in case of virtual paging, because the loop should be from the start index to the end index and the start index wouldn't be 0 on the second page.
I found this workaround..I am not sure if this is really foolproof, but it seems to work so far..if you know a more precise solution please post...
$("#jqxgrid").bind("bindingcomplete", function (event) {
var paginginfo = $("#jqxgrid").jqxGrid('getpaginginformation');
var pagenum = paginginfo.pagenum;
var pagesize = paginginfo.pagesize;
var pageRows = (pagenum + 1) * pagesize;
for (var i = 0; i < pageRows; i++) {
var value = $("#jqxgrid").jqxGrid('getcellvalue', i, 'currTrafDir');
if (value == 'W') { ......

Checking Postal Codes with JQuery

I try to build a form which checks if an entered zip code matches a zip code in a predefined array. I don't use a DB, it's all very basic and hardcoded, but should be sufficient in this case.
The problem is that only the first zip-code in the array ('83512') works. If i am entering the second one ('83533') the code spits out "no success".
What am I doing wrong?
Thanks in advance.
HTML:
<form action="javascript:alert('success.');" id="checkplz">
<label for="plz">ZIP:</label>
<input type="text" name="plz" id="plz" />
<button id="submit" >Check!</button>
<div id="output"></div>
</form>
JQuery:
$(document).ready(function(){
var list = ['83512','83533'];
$("#checkplz").submit(function() {
for (var i = 0; i < list.length; i++) {
if ($("#plz").val() == list[i]) {
$("#output").append("<strong class='success'>success!</strong>").show();
return true;
}
$("#output").text("no success!").show().fadeOut(10000);
return false;
}
});
});
The logic in your loop is off. See below:
$(document).ready(function(){
var list = ['83512','83533'];
$("#checkplz").submit(function() {
var match = false;
for (var i = 0; i < list.length; i++) {
if ($("#plz").val() == list[i]) {
$("#output").append("<strong class='success'>success!</strong>").show();
return true;
}
}
$("#output").text("no success!").show().fadeOut(10000);
return false;
});
});
The problem is within the logic of your loop. The loop will only run one time, because the loop will always return after the first iteration (true if it finds the first element in the list array, false for everything else), rather than continuing through all iterations. So, what is happening for the second element is that the loop is running, determining that the first element was not found and returning false and never even processing the second element.
A better way to do this would be to loop the list array until you find a matching element, and keep track of wether an match was found or not. This will make sure we don't drop out of the loop until we've processed all elements of the array (or found a match, in which case we can stop the loop to save on processing).
See below (http://jsfiddle.net/ryanbrill/Kws7A/) for some example code with a few comments about what is happening.
$(document).ready(function(){
var list = ['83512','83533'];
$("#checkplz").submit(function() {
var matched = false; // Set up variable to track if we find a match
$(list).each(function() {
// Inside the jQuery 'each' method, 'this' equals the current item in the iteration.
if(this == $("#plz").val()) {
matched = true; // set the 'matched' variable to true
$("#output").append("<strong class='success'>success!</strong>").show();
return; // Since we found a match, we can stop processing the array
}
});
// Outside of the loop, only display no success if we didn't find any matches.
if (!matched) {
$("#output").text("no success!").show().fadeOut(10000);
}
});
});
Try returning false outside the loop, so it will only happen once all values are checked:
$(document).ready(function(){
var list = ['83512','83533'];
$("#checkplz").submit(function() {
for (var i = 0; i < list.length; i++) {
if ($("#plz").val() == list[i]) {
$("#output").append("<strong class='success'>success!</strong>").show();
return true;
}
}
$("#output").text("no success!").show().fadeOut(10000);
return false;
});
});
Use jQuery.inArray()
var list = ['83512','83533'];
if($.inArray('83533', list) > -1){
// found
}
Docs here: http://api.jquery.com/jQuery.inArray/

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