473,395 Members | 1,790 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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(checkbox) //check if at least one checkbox is
selected
{
for(i=0; i<checkbox.length; 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(v1)) 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(checkbox) //OK: check if at least one checkbox is
selected
{
if(checkbox.length = "undefined") { // with single '=' !!!
if(checkbox.checked) {
return true;
}
} else {
for(i=0; i<checkbox.length; 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.length = "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 39399
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.javascript

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(checkbox) //check if at least one checkbox is
selected
{
for(i=0; i<checkbox.length; 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(check) {
var isChecked = false;

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

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

return isChecked;
}

if(checkbox.length = "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.length = "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(check) {
var isChecked = false;

if ((typeof check.length == 'undefined)&&(check.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.getElementsByName(strName) 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)&&(check.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(v1)) 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**********@yahoo.comwrote in message
news:11*********************@i42g2000cwa.googlegro ups.com...
>To make your code correct, you have to make it ready to accept both an
element reference and a collection reference:

function isAnyChecked(check) {
var isChecked = false;

if ((typeof check.length == 'undefined)&&(check.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.getElementsByName(strName) 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)&&(check.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(v1)) 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)&&(check.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)&&(check.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(v1)) 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)&&(check.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.javascript 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)&&(check.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)&&(check.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.javascript 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(v1)) 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**********@yahoo.comwrote in message
news:11**********************@f16g2000cwb.googlegr oups.com...
>
Oleg Konovalov wrote:
if ((typeof check.length == 'undefined)&&(check.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(v1)) 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)&&(check.checked)) {
}
else if (...) {
}
else {
}
}

Nov 12 '06 #10
VK
1) JavaScript runtime error: "v1" is undefined is coming from the
function call:
if (! isAnySelected(v1)) return false;
not from inside the function.
Are you sure that this check can fix that ?
Yes, I am: unless v1 was not declared anywhere in your program before
if (! isAnySelected(v1)) return false
"declared" would mean that somewhere in your program you have
var v1;
or
var v1 = something;
Also I see a strong "Java school" in this line (the famous
"truthulizer" joke about you, guys :-)
return isAnySelected(v1)
does the same as
if (! isAnySelected(v1)) return false
else return true
as you may guess

If v1 declared but has undefined value then inside the function you
trying to access the property of undefined : undefined.length and it
trigs the error. So first you check if v1 is not undefined and only
then you try to access a property of it. You may move the check level
up if you want (at the moment of the function call):
if (typeof v1 != 'undefined') { return isAnySelected(v1); }
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.
That depends on how are getting v1. Really: the whole HTTP page is
needed to see what and how are you doing (brought to the minimum case
if possible).

Nov 12 '06 #11
VK

VK wrote:
if (typeof v1 != 'undefined') { return isAnySelected(v1); }
Better:

return (typeof v1 != 'undefined') ? isAnySelected(v1) : false;
// otherwise with undefined v1 there will be no explicit
// return value which is dangerous.
// still posting the entire working page is more than
// suggested.

Nov 12 '06 #12
VK,

It would be very difficult to show the whole XSL page with all HTML &
Javascript,
it is a part of old large Cocoon/XSLT/Java application.

But the part related to v1 checkbox would be :

for each DB row (become XML nodes) - we are looping through them:
<input name="v1" type="checkbox">
<xsl:attribute name='value'><xsl:value-of
select='$therow/id'/></xsl:attribute>
</input>
--the value=therow/id to identify the row for operation on it
[like delete or modify or compare or display all detailed values]
So if the query returned no rows, there will be no instances of checkbox on
the page.

Hope it answers your question.

I will try your original and modified solutions tomorrow and let you know.

Thank you,
Oleg.
"VK" <sc**********@yahoo.comwrote in message
news:11**********************@k70g2000cwa.googlegr oups.com...
>
VK wrote:
> if (typeof v1 != 'undefined') { return isAnySelected(v1); }

Better:

return (typeof v1 != 'undefined') ? isAnySelected(v1) : false;
// otherwise with undefined v1 there will be no explicit
// return value which is dangerous.
// still posting the entire working page is more than
// suggested.

Nov 13 '06 #13
VK

Oleg Konovalov wrote:
But the part related to v1 checkbox would be :

for each DB row (become XML nodes) - we are looping through them:
<input name="v1" type="checkbox">
<xsl:attribute name='value'><xsl:value-of
select='$therow/id'/></xsl:attribute>
</input>
--the value=therow/id to identify the row for operation on it
[like delete or modify or compare or display all detailed values]
So if the query returned no rows, there will be no instances of checkbox on
the page.
This way the resulting HTML output will be like
<input type="checkbox" name="v1">Record 1</input>
<br>
<input type="checkbox" name="v1">Record 2</input>
<br>
<input type="checkbox" name="v1">Record 3</input>
(I'm sure you are using table rows instead, but for a short idea is
enough)

This way the suggested check could be (see comments inside):

<html>
<head>
<title>Checkboxes</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">

<script type="text/javascript">

function validate(refForm) {
var ret = false;

// ... other form validations ...

// Please note that "v1" is a string literal
// (form element name), not an object:
ret = isAnySelected(refForm.elements["v1"]);

return ret;
}
function isAnySelected(check) {
var ret = false;

// if at least one matching element found:
if (typeof check != 'undefined') {

// if several matching elements founds:
if (check.length) {
// intermediary var to speed up the loop:
var len = check.length;
for (var i=0; i<len; ++i) {
// if the element has boolean field "checked"
// and this field is set to true:
if ((typeof check[i].checked == 'boolean')
&& (check[i].checked)) {
ret = true;
break;
}
}
}

// if only one matching element found
// and the element has boolean field "checked"
// and this field is set to true:
else if (typeof check.checked == 'boolean') {
ret = check.checked;
}

// Else do nothing, just balance if-else clause:
else {
/*NOP*/
}

}

return ret;
}
</script>

</head>

<body>
<form method="POST" action="" onsubmit="return validate(this)">
<fieldset>
<input type="checkbox" name="v1">Record 1</input>
<br>
<input type="checkbox" name="v1">Record 2</input>
<br>
<input type="checkbox" name="v1">Record 3</input>
<br>
<input type="submit">
</fieldset>
</form>
</body>
</html>

Nov 14 '06 #14

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

Similar topics

6
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...
7
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,...
13
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...
49
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...
17
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
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...
2
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) { ...
11
by: redog6 | last post by:
Hello I have the above javascript error on filling in mandatory fields and submitting the form below: ...
4
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...

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.