473,614 Members | 2,377 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.getEl ementById("prod uct").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getEle mentById("produ ct").value;
}

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

Apr 13 '06 #1
9 220295

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

EG:

if (document.getEl ementById("prod uct").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getEle mentById("produ ct").value;
}

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


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

var productElement = document.getEle mentById("produ ct");

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.getEle mentById("produ ct");
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.getEl ementById("prod uct").value == null)
What element has an id of product and does that element have a .value
property?
{
prodValue = "";
}
else
{
prodValue = document.getEle mentById("produ ct").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.javas cript 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******** *************@u 72g2000cwu.goog legroups.com...
How do I check if an object exists in Javascript?

EG:

if (document.getEl ementById("prod uct").value == null)
{
prodValue = "";
}
else
{
prodValue = document.getEle mentById("produ ct").value;
}

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


if (document.getEl ementById("prod uct") == undefined)
{
prodValue = "";
}
else
{
prodValue = document.getEle mentById("produ ct").value;
}
Apr 13 '06 #4
[on] wrote:

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


why not

if (document.getEl ementById('prod uct')) {
// code here when the element exists
}

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

why not

if (document.getEl ementById('prod uct')) {
// code here when the element exists
}

or, untested but for efficiency,

if ( T = document.getEle mentById('produ ct') ) {
// code herein when the element exists, using T
}

or

if ( !(T = document.getEle mentById('produ ct') ) ) { 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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.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.supernew s.com>, dated Thu, 13 Apr
2006 09:56:00 remote, seen in news:comp.lang. javascript, Tony <tony23@ds
lextreme.WHATIS THIS.com> posted :
why not

if (document.getEl ementById('prod uct')) {
// code here when the element exists
}

or, untested but for efficiency,

if ( T = document.getEle mentById('produ ct') ) {
// code herein when the element exists, using T
}

or

if ( !(T = document.getEle mentById('produ ct') ) ) { 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.javas cript 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.getEle mentById("produ ct");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>


why not

if (document.getEl ementById('prod uct')) {
// 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.getEle mentById("produ ct");
> if (productElement != null)
> {
> // Code here when the Element Exists.
> }
> </code>


why not

if (document.getEl ementById('prod uct')) {
// 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.getEle mentById() 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.getEle mentById("produ ct");
if (productElement != null)
{
// Code here when the Element Exists.
}
</code>

why not

if (document.getEl ementById('prod uct')) {
// 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.getEle mentById() 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.getEle mentById('produ ct');
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
25613
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 one page to another and I might forget to change the form name, or an input tag name passed in the
3
13672
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
15433
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
2816
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
2572
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 == null)" line throws the error "Request is not available in this context".
2
2636
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 Description: An error occurred during the compilation of a resource required
0
1311
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
7671
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 below crashes since the dynamic Engine was deleted in the main. However, I need to clean up the...
2
9808
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
8176
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8120
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
8571
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
8265
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
7047
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
5537
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
4048
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2560
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
0
1420
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.