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

Undefined and null in Javascript

P: n/a
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
Share this Question
Share on Google+
13 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.