473,756 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Undefined and null in Javascript

Hi,

I am working on a web application which among other things uses DHTML, Java
and Javascript.
It populates web page based on the contents of the database (resultset),
and next to each row there is a checkbox (v1) allowing to select that row
for changes (e.g. delete, update, etc.)
So we are creating an array of checkbox, correct ?
Of course I have to check whether any of these checkboxes exist and if any
of them got selected (checked)
using Javascript before allowing any DB operation in Java.

Now it becomes strange.
I have noticed that if there is 1 row [i.e. 1 checkbox v1], that function
always shows warning and returns false:
function isAnySelected(c heckbox) //check if at least one checkbox is
selected
{
for(i=0; i<checkbox.leng th; i++) {
if(checkbox[i].checked) {
return true;
}
alert("You must choose at least one record.");
return false;
}
Why ? I call it as: onClick="if(! isAnySelected(v 1)) return false;"
I tried to fix that error, and noticed that in the case of a single row
checkbox.length is "undefined" .
So I modified that function into:

function isAnySelected(c heckbox) //OK: check if at least one checkbox is
selected
{
if(checkbox.len gth = "undefined" ) { // with single '=' !!!
if(checkbox.che cked) {
return true;
}
} else {
for(i=0; i<checkbox.leng th; i++) {
if(checkbox[i].checked) {
return true;
}
}
}
alert("You must choose at least one record.");
return false;
}

What I can't understand here is why that function works only when there is a
single '=' here:
if(checkbox.len gth = "undefined" )... ???
Checking for null produces Javascript errors or does nothing.

And how can I make it work if there are 0 rows [and thus 0 instances of
checkbox v1 ?]

Thank you in advance,
Oleg.
Oct 29 '06 #1
13 39439
Oleg Konovalov wrote:
....
I am working on a web application which among other things uses DHTML, Java
and Javascript.
When debugging JavaScript amd HTML, Java programmers
are the worst people to ask. Try..
comp.lang.javas cript

Andrew T.

Oct 29 '06 #2
VK
I am working on a web application which among other things uses DHTML, Java
and Javascript.
It populates web page based on the contents of the database (resultset),
and next to each row there is a checkbox (v1) allowing to select that row
for changes (e.g. delete, update, etc.)
So we are creating an array of checkbox, correct ?
"collection " is more appropriate as "array" implies a particular
programming entity which is not presented here.

<snip>
Now it becomes strange.
I have noticed that if there is 1 row [i.e. 1 checkbox v1], that function
always shows warning and returns false:
function isAnySelected(c heckbox) //check if at least one checkbox is
selected
{
for(i=0; i<checkbox.leng th; i++) {
if(checkbox[i].checked) {
return true;
}
alert("You must choose at least one record.");
return false;
}
Why ?
Because you are dealing here with the DOM 0 model for HTML forms and in
this model the internal call for a named form element is polymorphic:
If there is only one element with given name in given form, then a
reference to this element is returned. And HTML checkbox by default
doesn't have "length" property so it's properly reported as undefined.
If there are more than one element with given name in given form, then
a collection of all elements with this name is created and a reference
to this collection is returned. Respectively you have "length" property
set to the length of this collection.
To make your code correct, you have to make it ready to accept both an
element reference and a collection reference:

function isAnyChecked(ch eck) {
var isChecked = false;

if ((typeof check.length == 'undefined)&&(c heck.checked)) {
isChecked = true;
}

else {
for(var i=0; i<check.length ; i++) {
if (check[i].checked) {
isChecked = true;
break;
}
}

return isChecked;
}

if(checkbox.len gth = "undefined" ) { // with single '=' !!!
That's a fancy construct, it shows how careful you have to be with
conditions check in JavaScript and suggests to learn this language
better :-)

So you are getting (as explained earlier) a form checkbox reference so
it doesn't have "length" property. But in JavaScript if you make an
assignment to a non-existing property, it simply creates new property
with the given name and with the assignment value.
So you just created new property "length" with string value
"undefined" .
Assignment statements have their own return value: this is value of the
assignment result. So checkbox.length = "undefined" statement returns
string "undefined" and this is value thant if() block gets. But in
JavaScript any non-empty string in boolean checks is treated as true.
So effectively
if (checkbox.lengt h = "undefined" )
is equal to
if (true)
so the relevant branch is always executed. But in case of more than one
checkbox in the form is will produce run-time error because you are not
allowed to assign values to collection length, it's read-only.

Oct 29 '06 #3
VK
To make your code correct, you have to make it ready to accept both an
element reference and a collection reference:

function isAnyChecked(ch eck) {
var isChecked = false;

if ((typeof check.length == 'undefined)&&(c heck.checked)) {
isChecked = true;
}

else {
for(var i=0; i<check.length ; i++) {
if (check[i].checked) {
isChecked = true;
break;
}
}

return isChecked;
}
That is if keeping DOM 0 approach. You can also use
document.getEle mentsByName(str Name) method which is guaranteed to
return a collection in any case, even for a single element with such
name. The drawback is that this is a method of document, not a form. If
you have several forms on one page with uniformly named checkbox sets,
you'll end up by getting all checkboxes from all forms which is
definitely not what you want. IMHO DOM 0 approach is more robust and
portable.

Oct 29 '06 #4
Dear VK,

Thank you for your answer.
I tried to change my code to use your code change suggestion:
if ((typeof check.length == 'undefined)&&(c heck.checked)) {...
It works in most cases. However, when I have no checkboxes on the screen and
user still clicks that button,
I get JavaScript runtime error: "v1" is undefined.
It is coming from the call to that function itself:
if (! isAnySelected(v 1)) return false; where v1 is that (empty) collection
of checkboxes.

Is there any solution to that ?

Please help ! That became hot production issue for us today !

Thank you,
Oleg.

"VK" <sc**********@y ahoo.comwrote in message
news:11******** *************@i 42g2000cwa.goog legroups.com...
>To make your code correct, you have to make it ready to accept both an
element reference and a collection reference:

function isAnyChecked(ch eck) {
var isChecked = false;

if ((typeof check.length == 'undefined)&&(c heck.checked)) {
isChecked = true;
}

else {
for(var i=0; i<check.length ; i++) {
if (check[i].checked) {
isChecked = true;
break;
}
}

return isChecked;
}

That is if keeping DOM 0 approach. You can also use
document.getEle mentsByName(str Name) method which is guaranteed to
return a collection in any case, even for a single element with such
name. The drawback is that this is a method of document, not a form. If
you have several forms on one page with uniformly named checkbox sets,
you'll end up by getting all checkboxes from all forms which is
definitely not what you want. IMHO DOM 0 approach is more robust and
portable.

Nov 10 '06 #5
VK

Oleg Konovalov wrote:
if ((typeof check.length == 'undefined)&&(c heck.checked)) {...

It works in most cases. However, when I have no checkboxes on the screen and
user still clicks that button,
I get JavaScript runtime error: "v1" is undefined.
It is coming from the call to that function itself:
if (! isAnySelected(v 1)) return false; where v1 is that (empty) collection
of checkboxes.

Is there any solution to that ?

Please help ! That became hot production issue for us today !
I see you did not go through the Cornford's Boot-Camp School :-) (very
few who survives but these are all selected stubbering mf bastards :-)

The moral of programming: always be ready for the worst, be graceful
for anything better.

if (typeof check == 'object') {
if ((typeof check.length == 'undefined)&&(c heck.checked)) {
}
else if (...) {
}
else {
}
}

Nov 10 '06 #6
VK said the following on 11/10/2006 11:22 AM:
Oleg Konovalov wrote:
>>if ((typeof check.length == 'undefined)&&(c heck.checked)) {...
It works in most cases. However, when I have no checkboxes on the screen and
user still clicks that button,
I get JavaScript runtime error: "v1" is undefined.
It is coming from the call to that function itself:
if (! isAnySelected(v 1)) return false; where v1 is that (empty) collection
of checkboxes.

Is there any solution to that ?

Please help ! That became hot production issue for us today !

I see you did not go through the Cornford's Boot-Camp School :-) (very
few who survives but these are all selected stubbering mf bastards :-)

The moral of programming: always be ready for the worst, be graceful
for anything better.

if (typeof check == 'object') {
if ((typeof check.length == 'undefined)&&(c heck.checked)) {
Syntax Error.

Do you ever stop and wonder why nobody here listens to you (at least
anybody that knows better)

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 10 '06 #7
VK

Randy Webb wrote:
if (typeof check == 'object') {
if ((typeof check.length == 'undefined)&&(c heck.checked)) {

Syntax Error.

Do you ever stop and wonder why nobody here listens to you (at least
anybody that knows better)
The power of Christ upon of you...
Halloween triple booh on you...despite already passed...

Put the curly brackets jammed by Google in the needed order and leave
my soul in peace... :-)

Nov 10 '06 #8
VK said the following on 11/10/2006 3:14 PM:
Randy Webb wrote:
>>if (typeof check == 'object') {
if ((typeof check.length == 'undefined)&&(c heck.checked)) {
Syntax Error.

Do you ever stop and wonder why nobody here listens to you (at least
anybody that knows better)

The power of Christ upon of you...
Halloween triple booh on you...despite already passed...

Put the curly brackets jammed by Google in the needed order and leave
my soul in peace... :-)
Too bad it had nothing to do with "curly brackets" and everything to do
with 'undefined without the closing quote mark.

Some things speak for themselves.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 11 '06 #9
Guys,

Please don't argue on syntax !

I have no means of checking whether your suggestion will work or not on
weekend,
but honestly I have my doubts:

1) JavaScript runtime error: "v1" is undefined is coming from the
function call:
if (! isAnySelected(v 1)) return false;
not from inside the function.
Are you sure that this check can fix that ?

2) if (typeof check == 'object') {...
Hmm, do you mean that if that collection is not empty, it's an 'object' ?
Never thought of it that way.

I am primarily a Java/J2EE developer and use Javascript just occasionally,
and often find JS much more powerful and misterious than I thought. :-)

I appreciate your help.

Thank you again,
Oleg.

"VK" <sc**********@y ahoo.comwrote in message
news:11******** **************@ f16g2000cwb.goo glegroups.com.. .
>
Oleg Konovalov wrote:
if ((typeof check.length == 'undefined)&&(c heck.checked)) {...

It works in most cases. However, when I have no checkboxes on the screen
and
user still clicks that button,
I get JavaScript runtime error: "v1" is undefined.
It is coming from the call to that function itself:
if (! isAnySelected(v 1)) return false; where v1 is that (empty)
collection
of checkboxes.

Is there any solution to that ?

Please help ! That became hot production issue for us today !

I see you did not go through the Cornford's Boot-Camp School :-) (very
few who survives but these are all selected stubbering mf bastards :-)

The moral of programming: always be ready for the worst, be graceful
for anything better.

if (typeof check == 'object') {
if ((typeof check.length == 'undefined)&&(c heck.checked)) {
}
else if (...) {
}
else {
}
}

Nov 12 '06 #10

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

Similar topics

6
46575
by: John Ramsden | last post by:
.... when the id 'junk' doesn't exist anywhere in the document, instead of returning 'object'?! I am using Javascript for a drop-down menu, slightly adapted from one by Angus Turnbull (see http://javascript.internet.com and http://gusnz.cjb.net, not that this is probably relevant but it deserves a plug ;-), on Internet Explorer v6.0.2800.1106. I need this feature of getElementById(), or an equivalent one (using sound and standard...
7
2339
by: OzThor | last post by:
in javascript, is there a way to test if an array is undefined???? eg... for (var x=0; x<10; x++){ if test_array is undefined then x++ document.write(test_array) if anyone can help, thanks... oh and if you can get the syntex right for me thanks..
13
3085
by: Don Vaillancourt | last post by:
What's going on with Javascript. At the beginning there was the "undefined" value which represented an object which really didn't exist then came the null keyword. But yesterday I stumbled across "null" string. I know that I will get an "undefined" when I try to retrieve something from the DOM which doesn't exist. I have used null myself to initialize or reset variables. But in which
49
14518
by: matty | last post by:
Hi, I recently got very confused (well that's my life) about the "undefined" value. I looked in the FAQ and didn't see anything about it. On http://www.webreference.com/programming/javascript/gr/column9/ they say: <snip> The undefined property A relatively recent addition to JavaScript is the undefined property.
17
3348
by: yb | last post by:
Hi, Looking for clarification of undefined variables vs. error in JavaScript code. e.g. <script> alert( z ); // this will be an error, i.e. an exception </script>
45
4855
by: VK | last post by:
(see the post by ASM in the original thread; can be seen at <http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/3716384d8bfa1b0b> as an option) As that is not in relevance to "new Array() vs " question or to the array performance, I dared to move it to a new thread. Gecko takes undefined value strictly as per Book 4, Chapter 3, Song 9 of Books of ECMA :-)
2
1582
by: udieee | last post by:
Hi, When I run the following function in IE5.5 with SP2 (version 5.50.4807.2300.co ) I get the javascript error for 'undefined'' function checkParam(url, paramName, paramValue) { if(paramName!=undefined && paramValue!=undefined && paramName!=null && paramValue!=null && paramName.length==paramValue.length) {
11
8963
by: redog6 | last post by:
Hello I have the above javascript error on filling in mandatory fields and submitting the form below: http://www.wildwoodbushcraft.com/voucherformtest.htm?course_name=Bushcraft+Weekend+course&price_code=SWC This error only occurs in IE not firefox and I can't see anything wrong with the functioning of the form. I have been tearing my hair out on this one and would be very
4
8418
hemantbasva
by: hemantbasva | last post by:
We have designed an aspx page having five ajax tab in it. the data of first four are designed on page whereas for the fifth tab it renders a user control named MYDOMAIN. in the tab container's even onactivetabindexchanged we have called a method loadtabpanel() which is defined in javascript in same page.the problem is it sometime give the message load tab panel undefined. this error does not come regularly. it comes in usercontrol rendering . i...
0
9271
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
10031
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...
1
9838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9708
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
8709
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3805
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
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
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.