473,526 Members | 2,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check if object exists?

How do I check if an object exists in Javascript?

EG:

if (document.getElementById("product").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getElementById("product").value;
}

This gives me an 'object required' error...

Apr 13 '06 #1
9 220289

Chris Ashley wrote:
How do I check if an object exists in Javascript?

EG:

if (document.getElementById("product").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getElementById("product").value;
}

This gives me an 'object required' error...


So the element with the id "product" might not exist ?

var productElement = document.getElementById("product");

productElement should now either be the element or null, if it's null
you can't check "value" for it.

so:

<code>
var productElement = document.getElementById("product");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>

Apr 13 '06 #2
Chris Ashley said the following on 4/13/2006 5:26 AM:
How do I check if an object exists in Javascript?
With an if test.
EG:

if (document.getElementById("product").value == null)
What element has an id of product and does that element have a .value
property?
{
prodValue = "";
}
else
{
prodValue = document.getElementById("product").value;
}

This gives me an 'object required' error...


Then you probably do not have an ID of "product", or, that element does
not have a .value property.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 13 '06 #3
MB
"Chris Ashley" <ch***********@gmail.com> skrev i meddelandet
news:11*********************@u72g2000cwu.googlegro ups.com...
How do I check if an object exists in Javascript?

EG:

if (document.getElementById("product").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getElementById("product").value;
}

This gives me an 'object required' error...


if (document.getElementById("product") == undefined)
{
prodValue = "";
}
else
{
prodValue = document.getElementById("product").value;
}
Apr 13 '06 #4
[on] wrote:

<code>
var productElement = document.getElementById("product");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>


why not

if (document.getElementById('product')) {
// code here when the element exists
}

Apr 13 '06 #5
JRS: In article <12*************@corp.supernews.com>, dated Thu, 13 Apr
2006 09:56:00 remote, seen in news:comp.lang.javascript, Tony <tony23@ds
lextreme.WHATISTHIS.com> posted :

why not

if (document.getElementById('product')) {
// code here when the element exists
}

or, untested but for efficiency,

if ( T = document.getElementById('product') ) {
// code herein when the element exists, using T
}

or

if ( !(T = document.getElementById('product') ) ) { AbandonShip() }
// code hereon when the element exists, using T

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Apr 14 '06 #6
Dr John Stockton said the following on 4/14/2006 1:30 PM:
JRS: In article <12*************@corp.supernews.com>, dated Thu, 13 Apr
2006 09:56:00 remote, seen in news:comp.lang.javascript, Tony <tony23@ds
lextreme.WHATISTHIS.com> posted :
why not

if (document.getElementById('product')) {
// code here when the element exists
}

or, untested but for efficiency,

if ( T = document.getElementById('product') ) {
// code herein when the element exists, using T
}

or

if ( !(T = document.getElementById('product') ) ) { AbandonShip() }
// code hereon when the element exists, using T


The one drawback/possible failure would be in IE where you have an
element with a name or ID of T, then it would clash and crash. Other
than that, its ok code.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 14 '06 #7

Tony wrote:
[on] wrote:

<code>
var productElement = document.getElementById("product");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>


why not

if (document.getElementById('product')) {
// code here when the element exists
}


Mostly to show the user what's returning "null", and he wanted to grab
a value of the element later on. Though I could do what Dr Sockton
said, but I just don't "script/program" like that.

Apr 18 '06 #8
[on] wrote:
Tony wrote:
[on] wrote:
> <code>
> var productElement = document.getElementById("product");
> if (productElement != null)
> {
> // Code here when the Element Exists.
> }
> </code>


why not

if (document.getElementById('product')) {
// code here when the element exists
}


Mostly to show the user what's returning "null", and he wanted to grab
a value of the element later on. Though I could do what Dr Sockton
said, but I just don't "script/program" like that.


The reason is a different one. If you do the latter test, you will
have to retrieve the reference for the element object, i.e. call
document.getElementById() twice for the same argument. That is
unnecessarily inefficient.

However, comparing against `null' is not necessary, and, more important, not
complete. The method called is defined in W3C DOM Level 2+ to return
`null' if there is no such element. However, it is not defined what to
return if there is more than one element that applies (the return value is
defined to be undefined; this must be strictly distinguished from the
`undefined' value of ECMAScript implementations). Still it is reasonable
to assume that it will not be a true-value then. So the test should be a
type-converting one instead:

if (productElement)
{
... productElement ...
}
PointedEars
Apr 18 '06 #9
Thomas 'PointedEars' Lahn wrote:
[on] wrote:
Tony wrote:
[on] wrote:

<code>
var productElement = document.getElementById("product");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>

why not

if (document.getElementById('product')) {
// code here when the element exists
}
Mostly to show the user what's returning "null", and he wanted to grab
a value of the element later on. Though I could do what Dr Sockton
said, but I just don't "script/program" like that.


The reason is a different one. If you do the latter test, you will
have to retrieve the reference for the element object, i.e. call
document.getElementById() twice for the same argument. That is
unnecessarily inefficient.


I think it ultimately depends on what you're doing in the // code here
when the element exists - after all, it IS possible that you're not
doing something to that element :)

But - point taken. And that's something I may want to take a look at in
my own code.
However, comparing against `null' is not necessary, and, more important, not
complete. The method called is defined in W3C DOM Level 2+ to return
`null' if there is no such element. However, it is not defined what to
return if there is more than one element that applies (the return value is
defined to be undefined; this must be strictly distinguished from the
`undefined' value of ECMAScript implementations). Still it is reasonable
to assume that it will not be a true-value then. So the test should be a
type-converting one instead:

if (productElement)
{
... productElement ...
}


Would that be:
var productElement = document.getElementById('product');
if (productElement) ...

(just for clarity)
Apr 19 '06 #10

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

Similar topics

23
25594
by: Randell D. | last post by:
Folks, I have written some scripting tools that are compatable with alot of my pages - For example, I've created a script that will check to ensure certain form fields that require data, are completed. In order for this to work, I must pass it the form name, and the field names (input tag names). Sometimes I copy/paste the syntax from...
3
13649
by: Gareth Tonnessen | last post by:
I need to have a clean way to determine whether a query exists without trying to open it and getting an error message. Is there a simple way to determine whether an object exists in a database? Remove obvious from e-mail address. Gareth Tonnessen LuvTruth@att.netNOJUNK
6
15427
by: Darren Linsley | last post by:
I know this might seem like a dumb question, but how do you test that an object exists. Maybe i should explain a little. I have a variable that points to an object. Now if that oject is released, how can i test my variable to see if the object it was pointing at, still exists? Please help!!
1
2811
by: James | last post by:
vb.net 2003 i wrote a windows service that does threading. My codes are a) the service thread will read a list of machine from a text file (machines.txt). b) it then logon using the below Dim returnValue As Boolean = LogonUser(m_ntid, m_domain, m_pwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)
4
2566
by: Mark Berry | last post by:
Hi, I'm working on my "last resort" error block for a web application. If the error occurs after a Request has been made, I want to show the URL. If the Request object is not available, I'll skip it. I thought I could check for the existence of an object by comparing to null. However, in the global.asax code below, the "if (Request ==...
2
2632
by: tshad | last post by:
I have an object that may or may not exist on a page. Therefore, I test for it. But it doesn't seem to work if I do the following: if not HomeLink is nothing then HomeLink.NavigateUrl="http://www.staffingworkshop.com/" I get the error message: ******************************************************************** Compilation Error...
0
1306
by: Edwin.Madari | last post by:
updated creature running in its own thread will get you started. try it foryourself, change sleep times per your need. import os, sys, threading, time class Creature: def __init__(self, status): self.status = status self.state = 'run' def start(self): self.athread = threading.Thread(target=self.print_status)
4
7655
by: rickbird | last post by:
I have a composition object that is written in C++. The container class deletes the dynamic object in its destructor. However, if someone creates the object in the main and passes it to the container class, they will probably try to delete the dynamic object in their code. How do I test to see if the object exists before I delete it? The code...
2
9788
Manikgisl
by: Manikgisl | last post by:
HI. How to check File exists in Web Share C# try { WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx"); request.Method = "HEAD"; // Just get the document headers, not the data. request.Credentials = System.Net.CredentialCache.DefaultCredentials; // This may throw a WebException:
0
7329
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7602
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5779
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...
1
5174
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4815
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...
0
3313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
1702
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
1
888
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
549
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...

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.