getElementById with invalid ID causes script to exit?

B

bcr07548

I am writing a web site that uses JavaScript to validate certain forms
and I seem to be having some trouble. The site uses PHP and for one of
the forms, depending on the situation, one of of the text inputs does
not exist - the PHP doesn't generate the HTML for it. I wanted to have
the validation script check the length of the input if it exists but I
knew that I might have trouble if I tried to check the value of the
input without first checking that the input exists so I tried using
code similar to this:

if(document.getElementById("someId")!=null &&
document.getElementById("someId").value.length<8)
{
alert("String must be at least 8 characters.");
}

However, when I try that in Firefox (that's the only browser I've tried
so far), the validation script exits, the form is submitted with
errors, and I get a message in the JavaScript console saying that the
ID that I gave was invalid. I know it's invalid! That's why I checked
for null!

I thought that getElementById() would return null if the ID was
invalid. Is there any way to check if the input exists before
validating its value?

-Brandon R.
 
B

bruclan

the method 'document.getElementById("someId")' returns a Object's
reference.
so, 'document.getElementById("someId").value.length<8' should be
modified 'document.getElementById("someId").values.length<8'

just try it : )
 
M

Martin Honnen

if(document.getElementById("someId")!=null &&
document.getElementById("someId").value.length<8)
{
alert("String must be at least 8 characters.");
}

However, when I try that in Firefox (that's the only browser I've tried
so far), the validation script exits, the form is submitted with
errors, and I get a message in the JavaScript console saying that the
ID that I gave was invalid.

Please post the exact id value you pass to getElementById and post the
exact error message you get. Which version of Firefox is that?
 
R

Randy Webb

(e-mail address removed) said the following on 3/7/2006 7:37 AM:

Please quote what you are replying to.

If you want to post a followup via groups.google.com, don't use the
"Reply" link at the bottom of the article. Click on "show options" at
the top of the article, then click on the "Reply" at the bottom of the
article headers. said:
the method 'document.getElementById("someId")' returns a Object's
reference.

Only if the browser has an element with an ID of "someID".
so, 'document.getElementById("someId").value.length<8' should be
modified 'document.getElementById("someId").values.length<8'

just try it : )

And then come back and ask why it still doesn't work? There is no
..values property.
 
A

Amie

Hi,

Try with form name instead of getElementById.

document.formname1.textfieldname.value.length

should retrieve the length of the given field.

Amie
 
T

Thomas 'PointedEars' Lahn

Amie said:
Try with form name instead of getElementById.

document.formname1.textfieldname.value.length

should retrieve the length of the given field.

Generally:

document.forms["formname1"].elements["textfieldname"].value.length

Please search the archives before you post.


PointedEars
 
T

Thomas 'PointedEars' Lahn

I am writing a web site that uses JavaScript to validate certain forms
and I seem to be having some trouble.  The site uses PHP and for one of ^^^[1]
the forms, depending on the situation, one of of the text inputs does
not exist - the PHP doesn't generate the HTML for it. I wanted to have
the validation script check the length of the input if it exists but I
knew that I might have trouble if I tried to check the value of the
input without first checking that the input exists

You will definitely have trouble. A reference with a null base object
throws a ReferenceError exception.
so I tried using code similar to this:

Please post the _exact_ snippet, and the relevant parts of the
_generated_ HTML code[^1] the script is called from and operating on.
if(document.getElementById("someId")!=null &&
document.getElementById("someId").value.length<8)

This is highly inefficient. Try

// see also var o = document.getElementById("someId");

if (o && typeof o.value == "string" && o.value.length < 8)
{
alert("String must be at least 8 characters.");
}
[...]
However, when I try that in Firefox (that's the only browser I've tried
so far), the validation script exits, the form is submitted with
errors, and I get a message in the JavaScript console saying that the
ID that I gave was invalid. [...]

As Martin said.
I thought that getElementById() would return null if the ID was invalid.

Not quite.

Is there any way to check if the input exists before validating its value?

There is, see above.


PointedEars
 
B

bcr07548

Sorry. I was wrong. that code does work. When I was writing the
script to validate my form, I copied all of the names of the inputs
that I needed to validate and pasted them into my JS file before
writing the actual code to validate them. Apparently I forgot to
delete or comment out the list of variable names and that was what was
causing the problem, not my actual code.

The code itself works just fine. document.getElementById("someId")
gets a reference to the input with the ID "someId" and if that input
doesn't exist (the PHP didn't generated the HTML for it) then null is
returned and it doesn't bother trying to validate what doesn't exist.

Thanks for the replies though.
 
B

bcr07548

I thought that getElementById() would return null if the ID was invalid.

"If no such element exists, this returns null." ;-) It also says that
it doesn't throw an exception.
This is highly inefficient. Try

// see also var o = document.getElementById("someId");

if (o && typeof o.value == "string" && o.value.length < 8)
{
alert("String must be at least 8 characters.");
}

Worrying about the efficiency of *4 lines* of code written in an
*interpretted language* ?! I know there is a redundant lookup involved
in the example I gave but come on! I wouldn't be surprised if most
browsers kept track of id's and their associated objects in a binary
tree or hash map "behind the scenes" but even if they don't, calling
getElementById() a few extra times is not going to have a *noticable*
effect. You don't benchmark your JavaScript, do you? ;-)

By the way, using anything other than a boolean in a conditional
statement is horrible programming etiquette which is why some languages
don't even allow it. Unless the variable you are using in the
conditional statement was set to the result of a boolean operation, add
a comparison.

GOOD:
var o = document.getElementById("someId");
if (o != null) {}

GOOD:
var o = document.getElementById("someId");
var isValid = (o != null);
if (isValid) {}

NOT GOOD since 'o' is not a boolean:
if (o) {}

Using if(o) may work and may be a common shortcut but it's slop.
 
T

Thomas 'PointedEars' Lahn

(e-mail address removed) wrote:

Who wrote this? Please provide attribution of quoted material.
vvvvvvvvvvvvvvv
"If no such element exists, this returns null." ;-) It also says that
it doesn't throw an exception.

Read it again, _completely_.
Worrying about the efficiency of *4 lines* of code written in an
*interpretted language* ?!

It is a common misconception that ECMAScript implementations like JavaScript
are source code that is interpreted word by word. They are not. The
source code is parsed, compiled, and then the result of that process is
executed. At least SpiderMonkey, the JavaScript Reference Implementation
in Gecko-based UAs, works this way.

Furthermore, the language does not matter here. It is the repeated DOM
object reference retrieval that is unnecessary and makes the former
approach ineffcient.
I know there is a redundant lookup involved in the example I gave but come
on! I wouldn't be surprised if most browsers kept track of id's and their
associated objects in a binary tree or hash map "behind the scenes" but

But apparently they do not.
even if they don't, calling getElementById() a few extra times is not
going to have a *noticable* effect.

Yes, it is.
You don't benchmark your JavaScript, do you? ;-)

You would be surprised how consider techniques of efficient programming
speeds up especially DOM use. Obviously you have never benchmarked your
script code, and you have not been subscribed long enough to this
newsgroup.


PointedEars
 
B

bcr07548

I thought that getElementById() would return null if the ID was
Read it again, _completely_.

I assume you mean "if more than one element has an ID attribute with
that value, what is returned is undefined?" In this example, the
element that may or may not be output by the PHP code is in an
if-statement so either the element with the given ID is generated once
or not at all so you can be 100% certain that what is returned by
getElementById() will either be a reference to the object with the
given ID or null.
Furthermore, the language does not matter here. It is the repeated DOM
object reference retrieval that is unnecessary and makes the former
approach ineffcient.

Right. I even said that in my response but you are missing the point.
It's just a simple JavaScript and it runs more or less instantaneously
on any half-way modern machine.
But apparently they do not.

Apparently? I'm not saying that they do (because I haven't looked at
the browser code) but have you looked at all the code for Mozilla
either? It doesn't seem so far fetched seeing as a tree is build for
DOM nodes anyway.
Yes, it is.

So tell me, how many fractions of a millisecond does a getElementById()
call take. ;-)
You would be surprised how consider techniques of efficient programming
speeds up especially DOM use. Obviously you have never benchmarked your
script code, and you have not been subscribed long enough to this
newsgroup.

That was sarcasm. Of course I haven't benchmarked any of my
JavaScript. Maybe you are doing something more involved but my JS
usage is pretty much limited to scripts to validate forms and change
the visibility of a few elements based on what is checked or unchecked.
Even with a pretty reasonable number of inputs to validate, there are
no loops or recursion involved and even on the older machines I've
used, the code executes in less time that it would take for the next
page to download and the browser to display it. Maybe I'm the crazy
one but really working to optimizing JavaScript seems like such an
incredible waste of development time (and therefore money) considering
the payoff is that you might reduce execution time by a couple dozen
milliseconds. Save your optimization efforts for truly computationally
complex programming where you might actually save a few minutes or
hours of somebody's time.
 
T

Thomas 'PointedEars' Lahn

(e-mail address removed) wrote:

Please provide attribution of quoted material as layed out in the FAQ Notes.
vvvvvvvvvvvvvvvvvvvvvvvvvv
I assume you mean "if more than one element has an ID attribute with
that value, what is returned is undefined?"

So you finally found it.
In this example, the element that may or may not be output by the PHP code
is in an if-statement so either the element with the given ID is generated
once or not at all so you can be 100% certain that what is returned by
getElementById() will either be a reference to the object with the
given ID or null.

While your reasoning is still flawed (there may be another `if' statement
or that `if' statement may be executed in a loop), I can accept it
provisionally.
Right. I even said that in my response

You did not. And you are still referring to JavaScript only, in order to
be able to maintain your factually false statement of JavaScript being
interpreted source code where repetitions would not matter anyway. It is
not, and they do.
but you are missing the point.

I am not.
It's just a simple JavaScript and it runs more or less instantaneously
on any half-way modern machine.

So? That does not make any difference regarding efficiency of the code.
Apparently? I'm not saying that they do (because I haven't looked at
the browser code) but have you looked at all the code for Mozilla
either? It doesn't seem so far fetched seeing as a tree is build for
DOM nodes anyway.

A (document) tree /is/ build for DOM nodes. That is a matter of fact, and
was not debated. However, it does not have anything to do with your wild
assumption that node lookups are cached somehow, and therefore repeated
lookups of the same node would not matter much regarding runtime
efficiency. They /do/ matter, as tests have proven. So there is good
reason to believe that there is no implementation of such a lookup cache
in the tested user agents, including Gecko-based browsers. You do not
have to look at the source code of any of the tested UAs to come to that
conclusion.
So tell me, how many fractions of a millisecond does a getElementById()
call take. ;-)

A single Document::getElementById() call will not make much of a difference.
But _repeated_ lookups of the same item will do and in fact they do. It is
that difference in runtime efficiency that makes competent developers to
avoid developing the habit of doing repeated lookups of the same item in
the first place ...
[snipped]

.... but your further statements clearly indicate that you are no such person
(as yet).


PointedEars
 
B

bcr07548

In this example, the element that may or may not be output by the PHP code
While your reasoning is still flawed (there may be another `if' statement

Even if that if-statement were in another if-statement, that wouldn't
cause the element to be output multiple times - it would only make it
dependent on one more condition.
or that `if' statement may be executed in a loop),

Well, it's not. The function validates one particular form with one
optional input. Basically, what this comes down to is that the
precondition of getElementById() is that zero or one elements exist
with the given ID. This isn't a generic catch-all function that I am
writing to work with any form you can throw at it. In this case, the
preconditions are met, so it is safe to assume that getElementById()
will do what it is SUPPOSED to do. That's what preconditions are for!
"Give me what I was written for and I will give you what you expect."
You did not.

Actually, I did: "I know there is a redundant lookup involved in the
example I gave..."
A single Document::getElementById() call will not make much of a difference.
But _repeated_ lookups of the same item will do and in fact they do.

Well, this is a single extra lookup, which according to you won't make
much of a difference. Don't get me wrong. I agree entirely that basic
optimizations can be worthwhile - no sense in being wasteful just for
the sake of being wasteful - but your insistence on optimizing every
last line of code in a simple script at the expense of consistency is
coming off as troll-like.
It is
that difference in runtime efficiency that makes competent developers to
avoid developing the habit of doing repeated lookups of the same item in
the first place ...

If a lookup is only repeated once (when checking to see if the ONE
optional input exists), then one redundant lookup isn't such a bad
tradeoff for clean, consistent code. If I were writing a script that
were looping through all the elements on an entire page, saving the
reference would be wise (I'll give you that) but you can't look at four
lines of example code that gets run once when a form is submitted and
fly off the handle about efficiency.
[snipped]

... but your further statements clearly indicate that you are no such person
(as yet).

And you are one to talk based on:
- The way you use object references as booleans.
- Have no concept of relying on a function to do what its specs say
when its preconditions are met.
- Think that an if-statement in an if-statement might cause code to be
executed multiple times.
- Prefer optimization over consistency/readibility in every possible
case. Makes me think you only work independent on short scripts and
have never worked on a large project. Sure, saving the reference would
be great for more complex scripts but this is ONE lookup in a script
that is a hundred or so lines. You might be the biggest troll I've met
in a programming newsgroup in ages.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top