473,696 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HELP - select all checkbox javascript works fine.. unless there is only one checkbox.

We have an application to where you can select/deselect all checkboxes
in a checkbox array by clicking a 'master' checkbox at the top of the
screen. This seems to work fine unless there is only one checkbox
(these are dynamically generated). Why does this fail? If I do an
alert(field_to_ check.length) with 1 element in the array like this I
get 'Undefined'. Is this because this datatype is not an array if
there is only 1 element here? Thanks for any responses.

The function that checks the checkboxes is:

function check(this_fiel d, field_to_check)
{
var i;
if (eval(this_fiel d.checked))
{
for(i=0; i<field_to_chec k.length;i++)
field_to_check[i].checked=true;
return 1;
}
else
{
for(i=0; i<field_to_chec k.length;i++)
field_to_check[i].checked=false;
return 0;
}
}

The onClick event to this function is:
<input type='checkbox' name='check_all ' value=1 checked
onClick="check( this,
this.form.eleme nts['acct_num_list[]']);">

And the array of checkboxes when there is 1 element in them is:
<input class='copy' type='checkbox' name="acct_num_ list[]"
value='somethin g' checked>

Mike
Jul 23 '05 #1
4 6595
"Michael Champagne" <mc****@sbcglob al.net> wrote:
Is this because this datatype is not an array if
there is only 1 element here?


That's correct. So you need to check whether or not your object reference is
an array first, and treat it differently.
You can test if it's an array of checkboxes with something like:
function isCheckboxArray (obj) {
return ((typeof
obj.type!="stri ng")&&(obj.leng th>0)&&(obj[0]!=null)&&(obj[0].type=="checkbo x
"));
}

Also, I have a library which handles "checkbox groups" like this, including
this situation and others you may not have considered. You can check it out
at http://www.mattkruse.com/javascript/checkboxgroup/ if you wish!

--
Matt Kruse
Javascript Toolbox: http://www.mattkruse.com/javascript/
Jul 23 '05 #2
On 19 Apr 2004 13:13:37 -0700, Michael Champagne <mc****@sbcglob al.net>
wrote:
We have an application to where you can select/deselect all checkboxes
in a checkbox array by clicking a 'master' checkbox at the top of the
screen. This seems to work fine unless there is only one checkbox
(these are dynamically generated). Why does this fail? If I do an
alert(field_to_ check.length) with 1 element in the array like this I
get 'Undefined'. Is this because this datatype is not an array if
there is only 1 element here? Thanks for any responses.

The function that checks the checkboxes is:

function check(this_fiel d, field_to_check)
{
var i;
if (eval(this_fiel d.checked))
This eval() call is *really* not needed.
{
for(i=0; i<field_to_chec k.length;i++)
field_to_check[i].checked=true;
Duplicate code.
return 1;
I don't quite see the need to return a value, but it would be more
sensible to return a boolean, rather than a number.
}
else
{
for(i=0; i<field_to_chec k.length;i++)
field_to_check[i].checked=false;
return 0;
}
}

The onClick event to this function is:
<input type='checkbox' name='check_all ' value=1 checked
onClick="check( this,
this.form.eleme nts['acct_num_list[]']);">

And the array of checkboxes when there is 1 element in them is:
<input class='copy' type='checkbox' name="acct_num_ list[]"
value='somethin g' checked>


A revised and more compact version:

/* In-line this, if you prefer */
function isObject( r ) {
return( r && (( 'object' == typeof r ) ||
( 'function' == typeof r )));
}

function checkAll( group, check ) {
if( isObject( group )) {
if( group.length ) {
for( var i = 0, n = group.length; i < n; ++i ) {
group[ i ].checked = check;
}
} else {
group.checked = check;
}
}
/* Use "return check;" if you want to return the value set */
}

and the call would be modified to

checkAll( this.form.eleme nts[ 'acct_num_list[]' ], this.checked );

Hope that helps,
Mike

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #3
On Mon, 19 Apr 2004 15:36:00 -0500, Matt Kruse <ne********@mat tkruse.com>
wrote:
"Michael Champagne" <mc****@sbcglob al.net> wrote:
Is this because this datatype is not an array if
there is only 1 element here?
That's correct. So you need to check whether or not your object
reference is an array first, and treat it differently.


It'll be a collection, actually. Subtle difference.
You can test if it's an array of checkboxes with something like:
function isCheckboxArray (obj) {
return ((typeof
obj.type!="stri ng")&&(obj.leng th>0)&&(obj[0]!=null)&&(obj[0].type=="checkbo x
"));
}
I should think that

if( isObject( ref ) && ref.length ) {

is sufficient (using the isObject() definition from my post). It isn't in
all cases as a single object might have a length property, but it isn't
the case here.

If you were unsure of the type of elements returned in a collection, your
check wouldn't necessarily be reliable. It would be better to check the
type of each element in turn.

[OT]
Also, I have a library which handles "checkbox groups" like this,
including this situation and others you may not have considered. You can
check it out at http://www.mattkruse.com/javascript/checkboxgroup/ if
you wish!


I'm not trying to take sides in the debate that you and Richard are having
(I'm undecided, for the most part), but that script supports his point
against libraries. Whilst it might be a godsend under some circumstances,
it is undeniably overkill for the OP's problem. It would have been better
to point out the mistakes in the OP's code and give a distilled version of
your library function, rather than suggest it as it stands.

[/OT]

Mike

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #4
"Michael Winter" <M.******@bluey onder.co.invali d> wrote:
I'm not trying to take sides in the debate that you and Richard are having
(I'm undecided, for the most part), but that script supports his point
against libraries. Whilst it might be a godsend under some circumstances,
it is undeniably overkill for the OP's problem. It would have been better
to point out the mistakes in the OP's code and give a distilled version of
your library function, rather than suggest it as it stands.


That's a valid point, but I do disagree. The library referenced is only 4k,
so even with all the additional features, the size isn't something that will
overload any page.

And it's obvious from the original post that this user is somewhat of a
beginner (the use of eval, etc). I don't think that correcting this specific
example of code will teach the OP a lot about programming JS. However, I
think your response was undoubtedly helpful as well. The OP can decide which
will help him the most.

In the future, the OP might be back, asking how to modify the little snippet
of code he had to support different checkbox names, or pre-checked
checkboxes, etc. If not for this specific page, then possibly for future
pages, where the requirements are slightly different. If the user has my
library (or any other library) in their arsenal, they already have a
superset of problems solved. They can spend their time focusing on business
logic and functionality, rather than re-writing they code every time they
realize that they might want additional features.

For small libraries with very specific functionality - like this example - I
think that pointing someone to a reusable, generalized solution is a good
thing. Learning by examining existing solutions is how many of us learned a
lot of what we know :)

--
Matt Kruse
Javascript Toolbox: http://www.mattkruse.com/javascript/

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8418
by: Matt | last post by:
In ASP page, there is a "SELECT ALL" button, when user click it, it will select all checkboxes. I am not sure should I use client-side code to do that? the following is my approach but it didnt work. <script language="JavaScript"> function selectAllCheckBox() { //alert(document.addzone.c1.value); document.addzone.c1.value = "on"; } </script>
11
1552
by: Jack | last post by:
I have a asp form where among others there are few text boxes and one check box. The checkbox is to indicate whether the entry is final. The checkbox is attahced to a field in table of type yes/no. After saving the documents,the form is refreshed. At this point, if the checkbox has been saved with checked, it shows unchecked, if it has been saved unchecked it shows unchecked. Here, if the checkbox shows checked, I want to disable (or...
2
11680
by: Homa | last post by:
Hi, I have a Datagrid that uses as a shopping cart and have a checkbox template column in it. I can't add both OnCheckedChanged Event and onclick client script for it. I want to do two things: 1. I want the checkbox fires CheckedChanged event. I did this as
5
6437
by: Ed Jay | last post by:
This has to be easy, but I'm at a loss. In an externally linked js, I create a checkbox using innerHTML. How do I test the value or test to see if it's checked while still within the js? -- Ed Jay (remove M to respond by email)
1
2805
by: kebabkongen | last post by:
Hi, I'm working on a JavaScript that is enabling / disabling a select element according to whether a checkbox is selected or not. This works fine in Firefox, but in Internet Explorer (v 6.0.2900) it appears wierd: When I disable the selevt element in IE, it continues to appear as enabled (falsely) until I try changing it. When I click on it, updates itself as grey as to indicate that it is disabled.
17
3548
by: Timothy.Rybak | last post by:
Hello all, This is my first attempt at an application, so kid gloves are appreciated. I need to make a very simple form that only has a few elements. One is TraceCode - a text field that is populated when a user scans a label. The other is ScanDate - a date/time field that should equal the date/time of the scan (e.g. 7/31/2006 5:00:00 AM).
6
4306
by: D | last post by:
Hello all...I have an issue with one of my java script functions that I'm hoping someone can easily help with. I have a web based application that we use to create/sign up for overtime. When we have holidays we require our employees to sign up in 4 hr increments for the times we post. I'm having trouble creating a time slot that ends @ 12am. 12pm and all other hours work fine for start/end times. however 12am causes problems. My actual...
0
1512
by: rahulash | last post by:
I have a JSP showing data retreived from a database. This JSP is styled based on an XSL. The database returns data like student name, course, student remarks. I intend to add a checkbox which when checked would show student remarks and when unchecked would hide them. To do this I have made changes to the stylesheet. This is how the stylesheet is
0
5569
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
0
8666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8597
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9145
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9010
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8853
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4611
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2319
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1992
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.