By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,745 Members | 1,897 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,745 IT Pros & Developers. It's quick & easy.

Javascript accessing an array of checkboxes

P: n/a
In my HTML, I have several of the following:

<input type='checkbox' name='right[]' id='right[]' value='0' />

All are the same except the value is set differently for each one. The
reason for the [] is so I can access the checkbox values as an array on
the processing page (when clicking 'Submit');

However, I want my Javascript code to examine these objects first. My
onclick event handler function (below) is called (I get the 'hi there'
popup), but it does nothing afterward (i.e., neither 'checkbox' alert
appears, and the handler, strangely, seems to return 'true').

I suppose my problem is that I am not specifying the checkbox array
properly. I tried several variations, but I've been working on this
problem alone for several hours and am getting nowhere. Can someone show
me the correct syntax to do this, please. (My form name and id are set
to 'appl'...)

<script lang='JavaScript'>
function verifyAllChecked()
{
alert('hi there');
if(document.appl.right[0].checked == true) {
alert('checkbox is checked');
} else {
alert('checkbox is not checked');
}
return false;
}
</script>
Jan 15 '06 #1
Share this Question
Share on Google+
9 Replies


P: n/a
Rainman wrote:
In my HTML, I have several of the following:

<input type='checkbox' name='right[]' id='right[]' value='0' />

All are the same except the value is set differently for each one. The
reason for the [] is so I can access the checkbox values as an array on
the processing page (when clicking 'Submit');

However, I want my Javascript code to examine these objects first. My
onclick event handler function (below) is called (I get the 'hi there'
popup), but it does nothing afterward (i.e., neither 'checkbox' alert
appears, and the handler, strangely, seems to return 'true').

I suppose my problem is that I am not specifying the checkbox array
properly. I tried several variations, but I've been working on this
problem alone for several hours and am getting nowhere. Can someone show
me the correct syntax to do this, please. (My form name and id are set
to 'appl'...)

<script lang='JavaScript'>
The script element does not have a 'lang' attribute, though there is a
deprecated 'language' attribute. Just use the required type attribute:

<script type="text/javascript">
function verifyAllChecked()
{
alert('hi there');
if(document.appl.right[0].checked == true) {


if(document.appl.elements['right[]'].checked) {

or

if(document.forms['appl'].elements['right[]'].checked) {
Read "My element is named myselect[] , how do I access it?" in th FAQ:

<URL:http://www.jibbering.com/faq/#FAQ4_25>
[...]
--
Rob
Jan 16 '06 #2

P: n/a
> if(document.appl.elements['right[]'].checked) {

Excellent response... very helpful, especially the link you provided.
What worked for me is:

if(document.appl.elements['right[]',0].checked) {

Mark
Jan 16 '06 #3

P: n/a
Rainman wrote:
if(document.appl.elements['right[]'].checked) {

Excellent response... very helpful, especially the link you provided.
What worked for me is:

if(document.appl.elements['right[]',0].checked) {


That appears to be using a little-used feature of the HTMLCollections
interface[1]. If there is only one checkbox with that name, then:

if(document.appl.elements['right[]'].checked) {
will do the trick. However, if there is more than one checkbox with a
name of 'right[]' then:

document.appl.elements['right[]']
will return a collection, and since a collection doesn't have a checked
property, attempting to evaluate it returns 'undefined'.

Your method specifies an item number in the parameters to get the first
checkbox with that name:

document.appl.elements['right[]', 0].checked
The more common method is:

document.appl.elements['right[]'][0].checked
The advantage of your method is that it will return a reference to the
first right[] checkbox even if there is only one, whereas the other
method will cause an error if there is only one.

Did you stumble across it or read it in a reference somewhere? I would
not have deduced that behaviour from the spec, though both IE and
Firefox are consistent so I guess it's written clearly enough for
someone to understand.
1. <URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506>

--
Rob
Jan 16 '06 #4

P: n/a
Rainman <na**@yourdomain.com> writes:
if(document.appl.elements['right[]'].checked) {


Excellent response... very helpful, especially the link you
provided. What worked for me is:

if(document.appl.elements['right[]',0].checked) {


Quite by conicidence, though.

There is only one expression allowed inside a "square-bracket"
property accessor. You attempt to provide two, with a comma between
them, as if it was a method call with two arguments. That is not
what happens. This is correct syntax at all because of a little known
and used feature of Javascript (inherited from C along with much other
syntax baggage): a comma separated sequence of expressions is itself
an expression, and its value is the value of the last of the expressions.

In this case, your expression is equivalent to:
document.appl.elements[0].checked
This works as desired only if the first element named "right[]" is
also the first form control in the form at all.

More correct would be:
document.appl.elements['right[]'][0].checked
which takes merely the first element named "right[]", while assuming
that there are more than one.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jan 16 '06 #5

P: n/a
Lasse Reichstein Nielsen wrote:
More correct would be:
document.appl.elements['right[]'][0].checked
which takes merely the first element named "right[]", while assuming
that there are more than one.


And even more correct, being the standards compliant approach, would be

document.forms['appl'].elements['right[]'][0].checked

However, it appears that the method this piece of code is part of is for
common form data verification. Therefore:

<meta http-equiv="Content-Script-Type" content="text/javascript">
...
<script type="text/javascript">
function verifyAllChecked(f)
{
var result = false;

alert('hi there');

var o;
if (f && f.elements && (o = f.elements['right[]']))
{
// the OP probably wants a for-loop here
if (o[0].checked)
{
alert('checkbox is checked');
result = true;
}
else
{
alert('checkbox is not checked');
}

return result;
}
...
<form ... onsubmit="return verifyAllChecked(this);">
...
</form>

In that case, the form's name would not matter anymore.
PointedEars
Jan 16 '06 #6

P: n/a
Lasse Reichstein Nielsen wrote:
Rainman <na**@yourdomain.com> writes:

if(document.appl.elements['right[]'].checked) {


Excellent response... very helpful, especially the link you
provided. What worked for me is:

if(document.appl.elements['right[]',0].checked) {

Quite by conicidence, though.

There is only one expression allowed inside a "square-bracket"
property accessor. You attempt to provide two, with a comma between
them, as if it was a method call with two arguments. That is not
what happens. This is correct syntax at all because of a little known
and used feature of Javascript (inherited from C along with much other
syntax baggage): a comma separated sequence of expressions is itself
an expression, and its value is the value of the last of the expressions.

In this case, your expression is equivalent to:
document.appl.elements[0].checked
This works as desired only if the first element named "right[]" is
also the first form control in the form at all.


Thank you for clarifying that!

When calling a method surplus arguments are ignored (or in some languages
all stuffed into the last parameter). I expected expression property
accessors work the same way - nice to know why they don't.

[...]

--
Rob
Jan 16 '06 #7

P: n/a
Thomas 'PointedEars' Lahn wrote:
Lasse Reichstein Nielsen wrote:

More correct would be:
document.appl.elements['right[]'][0].checked
which takes merely the first element named "right[]", while assuming
that there are more than one.

And even more correct, being the standards compliant approach, would be

document.forms['appl'].elements['right[]'][0].checked

However, it appears that the method this piece of code is part of is for
common form data verification. Therefore:

<meta http-equiv="Content-Script-Type" content="text/javascript">
...
<script type="text/javascript">
function verifyAllChecked(f)
{
var result = false;

alert('hi there');

var o;
if (f && f.elements && (o = f.elements['right[]']))
{
// the OP probably wants a for-loop here
if (o[0].checked)

Wouldn't it be better here to see if o is a collection or not, then
optionally do a loop? Something like:
var oneChecked = false;

if (o){
if (o.length) {
for (var i=0, len=o.length; i<len && !oneChecked; ++i){
oneChecked = o[i].checked ;
}
} else {
oneChecked = o.checked;
}
alert('At least one right[] checked? ' + ((oneChecked)?'Yes':'No'));
}

[...]
--
Rob
Jan 16 '06 #8

P: n/a
Whoa!! Way more info than I was counting on! Thanks, though, as it is
all helpful. The notation:

document.appl.elements['right[]',0].checked

works for this, but it failed for the array of <textarea>s. What you
pointed out, namely the syntax of:

document.appl.elements['right[]'][0].checked

works correctly for both. I got the former syntax indirectly from RobG,
whose original reply to my post gave a link:

<URL:http://www.jibbering.com/faq/#FAQ4_25>

which had 3 more links for more information. The top one (I think) of
those had the format of the former.

Mark
Jan 16 '06 #9

P: n/a
RobG wrote:
Thomas 'PointedEars' Lahn wrote:
[...] it appears that the method this piece of code is part of is for
common form data verification. Therefore:

<meta http-equiv="Content-Script-Type" content="text/javascript">
...
<script type="text/javascript">
function verifyAllChecked(f)
{
var result = false;

alert('hi there');

var o;
if (f && f.elements && (o = f.elements['right[]']))
{
// the OP probably wants a for-loop here
if (o[0].checked)
Wouldn't it be better here to see if o is a collection or not, then
optionally do a loop?


It would definitely.
Something like:

var oneChecked = false;

if (o){
if (o.length) {
However, I am unsure as to whether this would suffice. There could be an
undocumented proprietary `length' property of the element object and this
method would fail then. What about this:

if (o.length && typeof o[0] == "object" && o[0])
{
for (var i=0, len=o.length; i<len && !oneChecked; ++i){
oneChecked = o[i].checked ;
}
} else {
oneChecked = o.checked;
}
alert('At least one right[] checked? ' + ((oneChecked)?'Yes':'No'));
}


I would exchange the two operands of the continue-condition of the `for'
statement, though; if we detect that at least one checkbox was checked,
it does not matter anymore if this was the last one or not.

Apart from that, well done.
PointedEars
Feb 16 '06 #10

This discussion thread is closed

Replies have been disabled for this discussion.