473,698 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getElementById with invalid ID causes script to exit?

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.get ElementById("so meId")!=null &&
document.getEle mentById("someI d").value.lengt h<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.

Mar 7 '06 #1
12 4041
the method 'document.getEl ementById("some Id")' returns a Object's
reference.
so, 'document.getEl ementById("some Id").value.leng th<8' should be
modified 'document.getEl ementById("some Id").values.len gth<8'

just try it : )

Mar 7 '06 #2


bc******@creigh ton.edu wrote:

if(document.get ElementById("so meId")!=null &&
document.getEle mentById("someI d").value.lengt h<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?

--

Martin Honnen
http://JavaScript.FAQTs.com/
Mar 7 '06 #3
br*****@163.com 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.c om, 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. <URL: http://www.safalra.com/special/googlegroupsreply/ >
the method 'document.getEl ementById("some Id")' returns a Object's
reference.
Only if the browser has an element with an ID of "someID".
so, 'document.getEl ementById("some Id").value.leng th<8' should be
modified 'document.getEl ementById("some Id").values.len gth<8'

just try it : )


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

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 7 '06 #4
Hi,

Try with form name instead of getElementById.

document.formna me1.textfieldna me.value.length

should retrieve the length of the given field.

Amie

Mar 7 '06 #5
Amie wrote:
Try with form name instead of getElementById.

document.formna me1.textfieldna me.value.length

should retrieve the length of the given field.


Generally:

document.forms["formname1"].elements["textfieldn ame"].value.length

Please search the archives before you post.
PointedEars
Mar 7 '06 #6
bc******@creigh ton.edu wrote:
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.get ElementById("so meId")!=null &&
document.getEle mentById("someI d").value.lengt h<8)
This is highly inefficient. Try

// see also news:68******** ********@Pointe dEars.de
var o = document.getEle mentById("someI d");

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.

<URL:http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-getElBId>
Is there any way to check if the input exists before validating its value?


There is, see above.
PointedEars
Mar 7 '06 #7
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.getEle mentById("someI d")
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.

Mar 9 '06 #8
> > I thought that getElementById( ) would return null if the ID was invalid.

Not quite.

<URL:http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-getElBId>


"If no such element exists, this returns null." ;-) It also says that
it doesn't throw an exception.
if(document.get ElementById("so meId")!=null &&
document.getEle mentById("someI d").value.lengt h<8)


This is highly inefficient. Try

// see also news:68******** ********@Pointe dEars.de
var o = document.getEle mentById("someI d");

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.getEle mentById("someI d");
if (o != null) {}

GOOD:
var o = document.getEle mentById("someI d");
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.

Mar 9 '06 #9
bc******@creigh ton.edu wrote:

Who wrote this? Please provide attribution of quoted material.
vvvvvvvvvvvvvvv
> I thought that getElementById( ) would return null if the ID was
> invalid. Not quite.

<URL:http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-getElBId>


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


Read it again, _completely_.
> if(document.get ElementById("so meId")!=null &&
> document.getEle mentById("someI d").value.lengt h<8)


This is highly inefficient. Try

// see also news:68******** ********@Pointe dEars.de
var o = document.getEle mentById("someI d");

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* ?!


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
Mar 9 '06 #10

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

Similar topics

3
36177
by: sofie | last post by:
Hello all, I use the following javascript function in a html document to set the level of one of eight available radiobuttons. The line that's commented out works fine under IE, but I need to rewrite it so that it's W3C compliant. Reading through earlier messages I concluded I should go with getElementById but this doesn't work. What am I doing wrong? Your help is much appreciated.
2
20932
by: Gary Mayor | last post by:
Hi, I'm back again. Basically i'm trying to draw a box over an image which is turning out to be a nightmare. The problem i'm getting at the moment is that i'm creating a line with <div which works when it's not hidden but I need to be able to make it hidden so I can use layers to show all when it finished drawing to make it smoother. This is how some other scripts are doing it that i've seen. So i've got it drawing a line and I need...
6
2138
by: MNF | last post by:
Hi everyone, I am using document.getElementById function in JavaScript to find a control within an html body, but instead I get back META item, because incidently the name of one meta tags is the same as the name of my control. It seems that it is by design, because getElementById returns the FIRST object with the same ID. What is the best general workaround to search control only within body? I prefer to allow control IDs be the same...
6
1510
by: lawrence | last post by:
I'm playing around with generating layer from a javascript. Strangely, the code below works fine in FireFox when I assign a color to 'color' but when I try to assign it to 'background-color' I get the error that you see below. What is up? <html> <head> </head> <body>
4
26589
by: Ghyslaine Crespe | last post by:
Hello, In my script, the line document.getElementById(id).style.background-position = "-200px -500px"; fails ! So, how can I change the background-position value ?
5
2241
by: FKothe | last post by:
Hello together, the program below shows a behavior i do not understand. When compiled with the HX-UX11 c-comiler ( version B.11.11.04 ) v2.p in function test_it0 points to an invalid adress and an attempt to write to this pointer causes the program to exit with a core dump. Output after compiling with HP c-compiler: 1. ffffff78 1. 7eff3358
20
6973
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
10
10392
by: Nik | last post by:
Hello! Thanks for reading my question first! I have many divs with an numeral id ,for example <div id="999">...</div>, <div id="1000">...</div> and I wish to do something like this, for( var i = startvalue; i<=endvalue; i++){ document.getElementById(i).style.background="yellow;"; }
10
3754
by: AC | last post by:
I had a page that does some event setup on window.onload: function prepEvents() { document.getElementById("menumap_sales").onmouseover = swapMenuSales; // etc } window.onload = prepEvents;
0
8603
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
9157
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...
0
9027
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8895
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
7725
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
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
3
2001
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.