Count check boxes

D

Daniel

Hello,

I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

I appreciate any guidance.

Thank you in advance,

D.
 
R

RobG

Hello,

I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of  the total number of
boxes and the number of checked.  Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

I appreciate any guidance.

Get all the input elements using getElementsByTagName:

<URL: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094 >

Use a loop to count the number of returned elements with type ==
'checkbox'. Within the same loop, if it's checkbox, count if checked
== true.

e.g. (quick 'n dirty code only)

function countEm(root) {
root = root || document;
var el, els = root.getElementsByTagName('input');
var countCBs = 0;
var countChecked = 0;
var i = els.length;

while (i--) {
el = els;

if (el.type == 'checkbox') {
++countCBs;

if (el.checked) {
++countChecked;
}
}
}

return {
'countCheckboxes': countCBs,
'countChecked': countChecked
};
}
 
G

Garrett Smith

Daniel said:
Hello,

I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

Give them the same name and a different value:

<input type="checkbox" name="booking" value="0">
<input type="checkbox" name="booking" value="1">
<input type="checkbox" name="booking" value="2">

A collection of those checkboxes can be got with:-

var bbs = <formref>.elements.booking;

The "total number" of the checkboxes in that collection is found from
the - length - property:

var bookingCount = bbs.length;

To find out which checkboxes in that collection are checked, loop
through them and read the - checked - property of each.

var r = [];
for(var i = 0; i < bookingCount; i++) {
if(bbs.checked) {
r.push(bbs.value);
}
}

Garrett
 
T

Thomas 'PointedEars' Lahn

Daniel:
I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

For example:

var numCBs = document.evaluate(
'.//input[@type="checkbox" and starts-with(@name, "booking[")]',
document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
.snapshotLength;

This should work in Firefox, Opera 9.64+, and Safari 4+, in HTML and XHTML
DOMs. (The number of checked checkboxes can be determined in the same way
if you add the corresponding attribute selector.)

<https://developer.mozilla.org/en/DOM/document.evaluate>

Use the document.getElementsByTagName() looping-and-filtering approach where
the above does not work (like IE; perform run-time feature tests, at least
before you call document.evaluate()).

Eschew XHTML; HTML 4.01 suffices in most cases and is much more compatible.


HTH

PointedEars
 
T

Thomas 'PointedEars' Lahn

Thomas said:
Daniel:
I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

For example:

var numCBs = document.evaluate(
'.//input[@type="checkbox" and starts-with(@name, "booking[")]',
document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
.snapshotLength;

This should work in Firefox, Opera 9.64+, and Safari 4+, in HTML and XHTML
DOMs. (The number of checked checkboxes can be determined in the same way
if you add the corresponding attribute selector.)

Apparently,

.//input[@type="checkbox" and @checked]

would only select the checkboxes that have the `checked' attribute set
(statically), not necessarily those that are currently checked. So with the
XPath approach you would need to iterate manually, too. However the number
of target nodes, thus the number of iterations, was significantly smaller
than with the getElementsByTagName("input") or the f.elements[...] approach:

var
checkboxes = document.evaluate(
'.//input[@type="checkbox" and starts-with(@name, "booking[")]',
document.body, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null),
cb,
count = 0;

while ((cb = checkboxes.iterateNext())) if (cb.checked) count++;


PointedEars
 
M

Martin Honnen

Thomas said:
var numCBs = document.evaluate(
'.//input[@type="checkbox" and starts-with(@name, "booking[")]',
document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
.snapshotLength;

This should work in Firefox, Opera 9.64+, and Safari 4+, in HTML and XHTML
DOMs.

No, in an XHTML DOM all XHTML elements are in the XHTML namespace
http://www.w3.org/1999/xhtml and //input with XPath 1.0 selects elements
with local name 'input' in _no_ namespace so it would not find any XHTML
input elements in an X(HT)ML DOM.
 
M

Matt Kruse

<input type="checkbox" name="booking" value="0">
<input type="checkbox" name="booking" value="1">
<input type="checkbox" name="booking" value="2">
A collection of those checkboxes can be got with:-
   var bbs = <formref>.elements.booking;

But be careful - this is only true if there is more than one checkbox
with the name 'booking'.

(If their number is dynamic and not known until run-time, you would
need to add additional logic to check for this)

Matt Kruse
 
E

Evertjan.

Matt Kruse wrote on 27 aug 2009 in comp.lang.javascript:
But be careful - this is only true if there is more than one checkbox
with the name 'booking'.

(If their number is dynamic and not known until run-time, you would
need to add additional logic to check for this)

or [more fun] by adding two invisible checkboxes that are always checked:

<input type="checkbox" name="booking" value="0">
<input type="checkbox" name="booking" value="1">
<input type="checkbox" name="booking" value="2">

div style='display:none;'>
<input type="checkbox" name="booking" value="-1" checked>
<input type="checkbox" name="booking" value="-2" checked>
</div>

var n = <formref>.elements.booking.length-2
 
T

Thomas 'PointedEars' Lahn

Martin said:
Thomas said:
var numCBs = document.evaluate(
'.//input[@type="checkbox" and starts-with(@name, "booking[")]',
document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
.snapshotLength;

This should work in Firefox, Opera 9.64+, and Safari 4+, in HTML and XHTML
DOMs.

No, in an XHTML DOM all XHTML elements are in the XHTML namespace
http://www.w3.org/1999/xhtml and //input with XPath 1.0 selects elements
with local name 'input' in _no_ namespace so it would not find any XHTML
input elements in an X(HT)ML DOM.

Correct, one would need something along

function nsResolver(prefix)
{
var ns = {
xhtml: "http://www.w3.org/1999/xhtml"
};

return ns[prefix] || null;
}

var
ns = document.documentElement.namespaceURI,
loc = './/xhtml:input[@type="checkbox" and starts-with(@name, "booking[")]',

numCBs = document.evaluate(
ns ? loc : loc.replace(/[a-z]+:/ig, ""),
document.body,
ns ? nsResolver : null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null)
.snapshotLength;

to handle this. WFM in Firefox/Iceweasel 3.5.1. See also the XPath
tutorial that I referred to.


PointedEars
 
G

Garrett Smith

Matt said:
On Aug 27, 1:02 am, Garrett Smith <[email protected]> wrote:

Was there something here?
But be careful - this is only true if there is more than one checkbox
with the name 'booking'.

Just before the example code, I wrote:-

"Give them the same name and a different value:"

Query sting sent to the server looks like:-

checkbox-finding.html?booking=-1&booking=-2

- and can be read by a program (Java here):-

String[] bookings = request.getParameterValues("booking");
if(bookings != null) {
/*we have an array, at least one was checked */
}

Giving the checkboxes the same name like this avoids HTML Errors.

Garrett
 
M

Matt Kruse

Was there something here?
?

Just before the example code, I wrote:-
"Give them the same name and a different value:"
Query sting sent to the server looks like:-
  checkbox-finding.html?booking=-1&booking=-2

I'm talking purely about js.
Your statement that "A collection of these checkboxes can be got
with: ... <formref>.elements.booking" is incorrect for the case where
there is only one checkbox with this name.

I was just pointing that out, in case the OP wasn't aware of this.
Giving the checkboxes the same name like this avoids HTML Errors.

And is a common practice. Unfortunately made more difficult with
checkboxes, since they are not submitted if not checked, so you need
extra server-side logic to detect when a checkbox has gone from
checked to unchecked.

Matt Kruse
 
G

Garrett Smith

Matt said:
I'm talking purely about js.
Your statement that "A collection of these checkboxes can be got
with: ... <formref>.elements.booking" is incorrect for the case where
there is only one checkbox with this name.

You're right. If there is one checkbox, then -
I was just pointing that out, in case the OP wasn't aware of this.


And is a common practice.

Well, ideally, but probably not common enough.

Unfortunately made more difficult with
checkboxes, since they are not submitted if not checked, so you need
extra server-side logic to detect when a checkbox has gone from
checked to unchecked.

Hardly.

The querystring sent to the server includes the checkboxes are checked,
and not the ones that are unchecked, and so to figure out which one is
not checked is done by seeing what is not there.

You snipped the code. I'll write it again and explain it below. I wrote:

| Query sting sent to the server looks like:-
|
| checkbox-finding.html?booking=-1&booking=-2
|
| - and can be read by a program (Java here):-
|
| String[] bookings = request.getParameterValues("booking");
| if(bookings != null) {
| /*we have an array, at least one was checked */
| }

The server knows which checkboxes were checked. It knows this by looking
at the values. We have two bookings in this case: "-1" and "-2". The
bookings that are not present were not checked.

Relying on a browser script would be foolhardy. If the user's browser
script is disabled or fails to execute (for whatever reason, and there
are plenty of cases wher ethis is true), then the server application
relying on that client side script will fail to perform as the monkey
who patched it intended.

HTML is all that is needed to send checkbox values to the server. Works
as designed.

Garrett
 
S

S.T.

Daniel said:
Hello,

I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

With JQuery, it's...

var i = $("input[name^='booking[']:checked").length;

.... plus, of course, the library which the user probably has cached
already from the Google CDN.

And you have to put up with half this newsgroup rambling about the pure
evil that is JQuery.
 
M

Matt Kruse


I stand by my statement.
The querystring sent to the server includes the checkboxes are checked,
and not the ones that are unchecked, and so to figure out which one is
not checked is done by seeing what is not there.

On the server, you can only know of two groups:
a) The boxes that were checked
b) The boxes that were never checked, OR went from checked to
unchecked

You cannot distinguish between the two cases in (b).

In order to know if a checkbox has gone from checked to unchecked, you
first need to know the original state on the server-side, then if the
value has not been submitted, you reason that it was unchecked. This
is the extra server-side logic required.

Based only on the form submission, you cannot say "give me the list of
checkboxes that are unchecked so I can update the database and remove
those records." You may get checkboxes included which were never
checked to begin with.

A common solution to this problem is to store the original state in
the session, so when the form is submitted you can compare to the
original state and easily figure out which checkboxes were unchecked.

And this is why checkboxes are often designed out of many systems ;)

Matt Kruse
 
E

Evertjan.

Matt Kruse wrote on 28 aug 2009 in comp.lang.javascript:
On the server, you can only know of two groups:
a) The boxes that were checked
b) The boxes that were never checked, OR went from checked to
unchecked

You cannot distinguish between the two cases in (b).

On the server, you can only know of two states:
x) The boxes that ARE checked at submit time
y) The boxes that ARE unchecked at submit time

The unchecked state can only be known
by knowing the html existense of the checkbox,
or a previous checked state of that box,
since unchecked information does get form-posted.
 
G

Garrett Smith

S.T. said:
Daniel said:
Hello,

I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of the total number of
boxes and the number of checked. Their synthax is

<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />

With JQuery, it's...

var i = $("input[name^='booking[']:checked").length;
Whatever that one line does, it is neither more efficient nor less error
than the reliable and standard approach posted.

That line of code almost attempst to answer the question. It might tell
how many are checked, so that would seem to address the "number of
checked" part of the question.

The first half of OP question:-
| guidance o how I can get an accurate count of the total number of
| boxes

Not that that isn't possible, but what is the reason for using such
inefficinet code when:

document.forms.myform.elements.booking

- is very clear.

The standard approach doesn't obscure what is going on and doesn't add
an extra jQuery.js and doesn't add the overhead of function calls.
... plus, of course, the library which the user probably has cached
already from the Google CDN.

And you have to put up with half this newsgroup rambling about the pure
evil that is JQuery.

You don't have to put up with anything. Stop the martyrdom and show us a
test of how much more efficient "the magic of jquery" is and why it is
more reliable.

Grow a pair and get a real name.

Garrett
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>
On the server, you can only know of two states:
x) The boxes that ARE checked at submit time
y) The boxes that ARE unchecked at submit time

The unchecked state can only be known
by knowing the html existense of the checkbox,
or a previous checked state of that box,
since unchecked information does get form-posted.

Not true, maybe, if client-side script can be used. On submit, copy the
state of all checkboxes to a string, and submit that string. UNTESTED.
If necessary, the string can be concealed in a well-placed
<input type=text
style="color:gray; background:gray; height:1px; width:1px">
which few readers will notice.

The record in the string could be made less noticeable by encoding it as
a sequence of whitespace characters.

Indeed, ISTM that one could record all changes to controls as they
occur, and so detect decisions that the customer dithered over.
 
P

Pherdnut

S.T. said:
Daniel said:
Hello,
I have a page which has a set of checkboxes and would like some
guidance o how I can get an accurate count of  the total number of
boxes and the number of checked.  Their synthax is
<input type="checkbox" name="booking[0]" value="1" />
<input type="checkbox" name="booking[1]" value="1" />
<input type="checkbox" name="booking[2]" value="1" />
With JQuery, it's...
  var i = $("input[name^='booking[']:checked").length;

Whatever that one line does, it is neither more efficient nor less error
than the reliable and standard approach posted.

That line of code almost attempst to answer the question. It might tell
how many are checked, so that would seem to address the "number of
checked" part of the question.

The first half of OP question:-
| guidance o how I can get an accurate count of  the total number of
| boxes

Not that that isn't possible, but what is the reason for using such
inefficinet code when:

document.forms.myform.elements.booking

- is very clear.

The standard approach doesn't obscure what is going on and doesn't add
an extra jQuery.js and doesn't add the overhead of function calls.
... plus, of course, the library which the user probably has cached
already from the Google CDN.
And you have to put up with half this newsgroup rambling about the pure
evil that is JQuery.

You don't have to put up with anything. Stop the martyrdom and show us a
test of how much more efficient "the magic of jquery" is and why it is
more reliable.

Grow a pair and get a real name.

Garrett

It's useful to try and work without frameworks as much as possible
until you've really honed your JS skills and knowledge. But there
comes a point where you're just being obstinate and completely missing
the point of actually using a framework. I'm saying this to you
because I was in the exact same mental boat as you clearly are now
until recently when I signed on with an all JQ shop where they'd
really rather you didn't DOM script 800 lines when you could do it in
a handful of JQ statements which do not obscure what's actually going
on if you know both JS and JQ.

On the flipside of that coin, JQ is not a workaround for actually
learning JavaScript. If you don't know what's really going on behind
the scenes you can very easily write painfully slow code. It's a lot
like regular expressions. It's powerful enough that if you don't know
what you're doing you can cripple your performance with a single line.

Trust me. JQ is badass. It gives you a lot more time in your day to do
things that you wouldn't have the energy or time for with plain
vanilla JS. It's not perfect but what, in our line of work, is?
 
T

Thomas 'PointedEars' Lahn

Pherdnut said:
On the flipside of that coin, JQ is not a workaround for actually
learning JavaScript.

Very true, because jQuery's author(s) have yet to learn scripting
themselves, especially in a browser context.
If you don't know what's really going on behind the scenes you can very
easily write painfully slow code.

You can even do this while knowing that.
It's a lot like regular expressions.

Most of the time for no good reason.
It's powerful enough that if you don't know what you're doing you can
cripple your performance with a single line.

It's written ambiguously and cluelessly enough that not even its main author
really knows what it does most of the time (does `attr' ring a bell?).
Trust me. JQ is badass. It gives you a lot more time in your day to do
things that you wouldn't have the energy or time for with plain vanilla
JS. It's not perfect but what, in our line of work, is?

jQuery is junk, you are not quite there yet if you promote it (especially
here where it has been literally discussed to death), and they are fools for
trusting it with their production code. For it is painfully inefficient
(slow, memory-expensive, bloated) and incompatible *inside*, and the next
time it encounters an unknown, but reasonably standards-compliant browser,
it might as well break.

Ultimately, it leads to a quite dangerous dependency, to code that does
everything with jQuery, even if a few, much more readable and maintainable
lines without jQuery would have sufficed; like the saying goes, if all you
know is to use a hammer, every problem looks like a nail. I've seen it before.

Please trim your quotes to the necessary minimum required to retain context.

<http://jibbering.com/faq/#posting>


PointedEars
 
P

Pherdnut

jQuery is junk, you are not quite there yet if you promote it (especially
here where it has been literally discussed to death), and they are fools for
trusting it with their production code.  For it is painfully inefficient
(slow, memory-expensive, bloated) and incompatible *inside*, and the next
time it encounters an unknown, but reasonably standards-compliant browser,
it might as well break.

Ultimately, it leads to a quite dangerous dependency, to code that does
everything with jQuery, even if a few, much more readable and maintainable
lines without jQuery would have sufficed; like the saying goes, if all you
know is to use a hammer, every problem looks like a nail.  I've seen itbefore.

Well, I can only speak from experience. I write code for a major
retailer with a lousy offshoring strategy for the backend (they
actually do much of the back end work on the front end which means we
don't have full control among other insanely wrong things about that
situation) and it's a massive, bloated site with literally thousands
of lines in the HTML on every page, most of which are whitespace left
in place by a hopelessly outdated version of IBM's lovely WebSphere
Ecommerce application. Barring some serious staffing changes we will
not be serving valid pages any time soon. So yes, there's a lot of
stuff for JQ to trip over on our site.

When I was still pretty new I rewrote our carousel code from scratch
because the old one (written by another hacktacular offshore team) was
actually making the entire page choke when you resized the windows
among many other frustrating things. What I was not prepared for was
the sheer volume of our site and the fact that we literally had a
carousel or four (in one case) on just about every single possible
page vaguely relating to the browsing of products. Literally dozens of
implementations.

Overriding style sheets in places they didn't belong has been a
nightmare. Details concerning the data that gets fed into the page
from a third party and keeps breaking because our markup gets
overwritten all the time has been a nightmare. The offshore guys doing
that thing they do where they add a million checks for whether
incoming data is valid "just in case" has been a nightmare (do they
get that from Java or something?).

Yet nothing internal to that object I wrote with a lot of JQ has been
a problem on any browser. It lazy loads items as you scroll. It's
elastic with auto-margin expansion and item auto-inserting action as
you resize. The animations are smooth. It handles vertical and
horizontal carousels. And it has more options for alternate behavior
than I really want to go into. That seems pretty stable to me.

But then, perhaps you're right and I'm not 'there yet' by which I
assume you mean, where you are, which would explain why I'm not having
the same problems with the framework you've had. Perhaps when I'm
closer to your lofty perch I'll be attempting the sorts of acts of
JavaScript wizardry that enable one to see how hopelessly bloated
JQuery, an actively-maintained 15K framework the size of medium-ish
jpeg, truly is.

I was not aware of any issues with attr as I spend more time using JQ
than arguing about it. Links are helpful as Google has not been.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top