473,598 Members | 3,244 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 220294

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
13671
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
15432
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
2571
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
2634
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
1310
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
7670
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
9807
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
8398
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
8400
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
8051
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
8267
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6725
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
5438
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
3898
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...
0
3940
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2414
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

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.