473,545 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript accessing an array of checkboxes

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='JavaScrip t'>
function verifyAllChecke d()
{
alert('hi there');
if(document.app l.right[0].checked == true) {
alert('checkbox is checked');
} else {
alert('checkbox is not checked');
}
return false;
}
</script>
Jan 15 '06 #1
9 2075
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='JavaScrip t'>
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 verifyAllChecke d()
{
alert('hi there');
if(document.app l.right[0].checked == true) {


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

or

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

<URL:http://www.jibbering.c om/faq/#FAQ4_25>
[...]
--
Rob
Jan 16 '06 #2
> if(document.app l.elements['right[]'].checked) {

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

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

Mark
Jan 16 '06 #3
Rainman wrote:
if(document.app l.elements['right[]'].checked) {

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

if(document.app l.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.app l.elements['right[]'].checked) {
will do the trick. However, if there is more than one checkbox with a
name of 'right[]' then:

document.appl.e lements['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.e lements['right[]', 0].checked
The more common method is:

document.appl.e lements['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
Rainman <na**@yourdomai n.com> writes:
if(document.app l.elements['right[]'].checked) {


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

if(document.app l.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.e lements[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.e lements['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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jan 16 '06 #5
Lasse Reichstein Nielsen wrote:
More correct would be:
document.appl.e lements['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 verifyAllChecke d(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="retur n verifyAllChecke d(this);">
...
</form>

In that case, the form's name would not matter anymore.
PointedEars
Jan 16 '06 #6
Lasse Reichstein Nielsen wrote:
Rainman <na**@yourdomai n.com> writes:

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


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

if(document.a ppl.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.e lements[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
Thomas 'PointedEars' Lahn wrote:
Lasse Reichstein Nielsen wrote:

More correct would be:
document.appl.e lements['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 verifyAllChecke d(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
Whoa!! Way more info than I was counting on! Thanks, though, as it is
all helpful. The notation:

document.appl.e lements['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.e lements['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.c om/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
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 verifyAllChecke d(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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2450
by: daniel | last post by:
Hi, This is more a javascript than a PHP problem, but anyway, if anyone can help.... I have a script that will dynamically create a series of checkboxes according to the number of values in the database (a pricelist). The checkboxes are created with a naming convention from cb1 to cbx (x being the number of records returned).
3
6778
by: Nath | last post by:
Please help!? I am new to writing html, javascript, pretty new to MySQL but quite proficient at writing Perl and i'm a quick learner. I am building a database driven website and i am a little stuck: I have page of results obtained from a MySQL query presented as a table (the first column having checkboxes for each of the rows in the table,...
6
2726
by: Chris Styles | last post by:
Dear All, I've been using some code to verify form data quite happily, but i've recently changed the way my form is structured, and I can't get it to work now. Originally : The form is called "form1", and I have selects called "PORTA", "PORTB" ... etc...
22
4576
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and...
1
8494
by: Oleg Konovalov | last post by:
Hi, I am trying to pass a bunch of checked checkboxes (Javascript array) from page1 to the Java action class on subsequent web page (page2). (on page 1 I have a bunch of DB rows with a checkbox, need to iterate through pages page2 - e.g. allow user to update the fields there) On page1 I have a bunch of checkboxes with the same name v1...
24
6294
by: firstcustomer | last post by:
Hi, Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that someone will be able to point me to a ready-made solution to my problem! A friend of mine (honest!) is wanting to have on his site, a Javascript Calculator for working out the cost of what they want, for example: 1 widget and 2 widglets = £5.00
3
7353
by: DFDavis | last post by:
I have a bunch of dynamically created checkboxes that I add to the a label in the html through my C# code. Then I also have a javascript function that goes through and identifies which checkboxes are checked when the user clicks on the submit button. My question now is, how would I go about getting the list of checked boxes back to my C#...
2
5536
by: HockeyFan | last post by:
Yesterday, I posted a question dealing with an issue of trying to reference (from javascript on the client side) an item within a Repeater. My code was hard-coded to use the actual ClientId, but someone admonished me, stating that I shouldn't do that because the id could change. However, since I'm trying to reference a control on a Repeater...
16
6290
by: sarega | last post by:
Hi, There is an array whose length varies dynamically on the users input, I have to provide checkboxes for this array along with the value of the array and based on the checkboxes selected by the user the value of that checkbox has to be retrived back at the php code for further processing. NOTE:The value of the array x changes dynamically, here...
0
7420
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7934
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7778
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6003
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5349
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3459
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1033
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
731
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.