Undefined and null in Javascript

O

Oleg Konovalov

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.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.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.
 
A

Andrew Thompson

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.
 
V

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.

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.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.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.
 
V

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.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.
 
O

Oleg Konovalov

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 said:
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.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.
 
V

VK

Oleg said:
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 {
}
}
 
R

Randy Webb

VK said the following on 11/10/2006 11:22 AM:
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)
 
V

VK

Randy said:
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... :)
 
R

Randy Webb

VK said the following on 11/10/2006 3:14 PM:
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.
 
O

Oleg Konovalov

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.
 
O

Oleg Konovalov

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.
 
V

VK

Oleg said:
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.checked == 'boolean')
&& (check.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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top