473,765 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to reference an element passed by ID to function using getElementByID

JJA
I'm trying to use document.getEle mentByID inside a function where the
ID is passed as an argument. I get the same error ("Element has no
properties") on the same statement inside the commonCheck function
with either MS IE 6.0 or Mozilla Firefox 0.9. Comments below indicate
that if I hardcode an element ID I can avoid the error, but I
obviously want to parameterize it. Here are some snippets of my code:

-----snippet 1-------------------------------------------------------
<form method="POST" action="UserPro fileMaint.htm"
onSubmit="retur n validateTelnr ("txtPhone", "msgPhone", true);">
<p>&nbsp;</p>
<p>&nbsp;</p>
<table id="tblMain" border="0" width="100%">
<tr>
<td width="25%">&nb sp;</td>
<td width="25%">Pho ne</td>
<td width="25%"><in put type="text" name="txtPhone" id="txtPhone"
size="20"></td>
<td width="25%"><in put type="hidden" name="msgPhone"
id="msgPhone"> </td>
</tr>
-----snippet 2-------------------------------------------------------
function validateTelnr (vfld, // element to be validated
ifld, // id of element to receive
info/error msg
reqd) // true if required
{
var stat = commonCheck (vfld, ifld, reqd);
-----snippet 3-------------------------------------------------------
function commonCheck (vfld, // element to be validated
ifld, // id of element to receive
info/error msg
reqd) // true if required
{
if (!document.getE lementById)
return true; // not available on this browser - leave validation
to the server

var elem = document.getEle mentById(ifld); // this will fail on next
stmt
//var elem = document.getEle mentById("txtPh one"); //COMMENTED OUT:
this works
if (!elem.firstChi ld) //------> fails here with msg "elem has no
properties"
return true; // not available on this browser
if (elem.firstChil d.nodeType != node_text)
return true; // ifld is wrong type of node

if (emptyString.te st(vfld.value)) {
if (reqd) {
msg (ifld, "error", "ERROR: required");
vfld.focus();
return false;
}
Jul 23 '05 #1
10 2691
JJA wrote:
I'm trying to use document.getEle mentByID inside a function where the [snip] <td width="25%">&nb sp;</td>
<td width="25%">Pho ne</td>
<td width="25%"><in put type="text" name="txtPhone" id="txtPhone"
size="20"></td>
<td width="25%"><in put type="hidden" name="msgPhone"
id="msgPhone"> </td>
</tr>

[snip]

Please replace tabs with spaces (2 per tab is nice), and manually
wrap your lines at about 65 characters (allows for a couple of sets
of reply quotes).

Then re-post your code. I can't tell if the errors are my attempt
to fix the format or your coding.

Cheers, Rob.
Jul 23 '05 #2
JJA wrote:

[snip]
onSubmit="retur n validateTelnr ("txtPhone", "msgPhone", true);"> [snip] function validateTelnr (vfld,ifld,reqd ) [snip] var stat = commonCheck (vfld, ifld, reqd); [snip] function commonCheck (vfld,ifld,reqd ) [snip] var elem = document.getEle mentById(ifld); // this will fail on next
// stmt
//var elem = document.getEle mentById("txtPh one"); //COMMENTED OUT:
//this works
if (!elem.firstChi ld) //------> fails here with msg "elem has no
// properties"


If I have re-formatted your code right (chances are I haven't), you are
putting "txtPhone" into vfld when you call validateTelnr() . You then
keep passing the variables on subsequent calls using the same names
each time.

When you get down to snippet 3, you are expecting "txtPhone" to be in
variable ifld - but you seem to have kept putting it into vfld.

vfld (I think) is getting the string "msgPhone", a hidden input field
that has a *name* but no *id*, so there is no id="msgPhone" and the
call returns nothing - exactly as it should.

A simple debug is to put an alert just before you use a variable to
find out what its value is at the critical moment, either working
backwards from the failure or forwards from the top to see where in
breaks. In this case, a line like:

alert(' vfld is: ' + vfld
+ '\n ifld is: ' + ifld
+ '\n reqd is: ' + reqd);

would have shown it was right at the start...

Hope that helps - Rob.
Jul 23 '05 #3
There is no problem of using getElementById whith passed arguments, try this:
<a id="o22" href="#">asda</a><script>
function ig(id){
document.getEle mentById(id).st yle.visibility = 'hidden';
}
ig('o22');
</script>
A posible problem is calling the function passing an object instead of an string:

<script>
ig('o22'); // Correct (passing an string)
ig(o22); // Bad (passing an object (variable))
</script>

jo***@cbmiweb.c om (JJA) wrote in message news:<2c******* *************** ****@posting.go ogle.com>...
I'm trying to use document.getEle mentByID inside a function where the
ID is passed as an argument. I get the same error ("Element has no
properties") on the same statement inside the commonCheck function
with either MS IE 6.0 or Mozilla Firefox 0.9. Comments below indicate
that if I hardcode an element ID I can avoid the error, but I
obviously want to parameterize it. Here are some snippets of my code:

-----snippet 1-------------------------------------------------------
<form method="POST" action="UserPro fileMaint.htm"
onSubmit="retur n validateTelnr ("txtPhone", "msgPhone", true);">
<p>&nbsp;</p>
<p>&nbsp;</p>
<table id="tblMain" border="0" width="100%">
<tr>
<td width="25%">&nb sp;</td>
<td width="25%">Pho ne</td>
<td width="25%"><in put type="text" name="txtPhone" id="txtPhone"
size="20"></td>
<td width="25%"><in put type="hidden" name="msgPhone"
id="msgPhone"> </td>
</tr>
-----snippet 2-------------------------------------------------------
function validateTelnr (vfld, // element to be validated
ifld, // id of element to receive
info/error msg
reqd) // true if required
{
var stat = commonCheck (vfld, ifld, reqd);
-----snippet 3-------------------------------------------------------
function commonCheck (vfld, // element to be validated
ifld, // id of element to receive
info/error msg
reqd) // true if required
{
if (!document.getE lementById)
return true; // not available on this browser - leave validation
to the server

var elem = document.getEle mentById(ifld); // this will fail on next
stmt
//var elem = document.getEle mentById("txtPh one"); //COMMENTED OUT:
this works
if (!elem.firstChi ld) //------> fails here with msg "elem has no
properties"
return true; // not available on this browser
if (elem.firstChil d.nodeType != node_text)
return true; // ifld is wrong type of node

if (emptyString.te st(vfld.value)) {
if (reqd) {
msg (ifld, "error", "ERROR: required");
vfld.focus();
return false;
}

Jul 23 '05 #4
On 14 Oct 2004 19:59:33 -0700, JJA <jo***@cbmiweb. com> wrote:
I'm trying to use document.getEle mentByID inside a function where the ID
is passed as an argument.
Based on what you've shown, you don't need to. Instead, use the elements
collection for the containing form:

document.forms['formNameOrId'].elements[ ... ]

If the form you've posted is the only one, you could also use

document.forms[0].elements[ ... ]

The elements collection will try to find id matches first, but if none can
be found it will try names.
I get the same error ("Element has no properties") on the same statement
inside the commonCheck function with either MS IE 6.0 or Mozilla Firefox
0.9.
I can't honestly say why. There's nothing obvious in the code you show
that would cause the behaviour you describe. It's already been suggested
that you use alerts to check the values of the function arguments at each
stage, and I think that would be a good thing to do.

What is causing your problem is that the value you pass to getElementById
doesn't represent a id that the browser can find. You'll have to look at
why that happens.

[snip]
if (!elem.firstChi ld)
return true;
if (elem.firstChil d.nodeType != node_text)
return true; // ifld is wrong type of node


You do realise that this will always fail for INPUT elements, don't you.

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Lee
JJA said:

I'm trying to use document.getEle mentByID inside a function where the
ID is passed as an argument. I get the same error ("Element has no
properties") on the same statement inside the commonCheck function
with either MS IE 6.0 or Mozilla Firefox 0.9. Comments below indicate
that if I hardcode an element ID I can avoid the error, but I
obviously want to parameterize it. Here are some snippets of my code:

-----snippet 1-------------------------------------------------------
<form method="POST" action="UserPro fileMaint.htm"
onSubmit="retur n validateTelnr ("txtPhone", "msgPhone", true);">


txtPhone and msgPhone are NOT the id's of any elements.
They are the names of form fields. That's very different.
You shouldn't be passing either one though, you should pass
references to these elements:

onsubmit="retur n validateTelnr(t xtPhone, msgPhone, true)"

Then, within the validation code, you don't need to mess with firstChild()
or nodeType() methods, you simply access the value attribute of the
form field:

if (emptyString.te st(vfld.value)) {
...
}

Jul 23 '05 #6
On 15 Oct 2004 07:36:05 -0700, Lee <RE************ **@cox.net> wrote:

[snip]
txtPhone and msgPhone are NOT the id's of any elements.


Actually, they are. Look closer at the contents of the table.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #7
JJA
el************@ gmail.com (Eloi de San Mart?n Lagranje) wrote in message news:<f9******* *************** ****@posting.go ogle.com>...
There is no problem of using getElementById whith passed arguments, try this:
<a id="o22" href="#">asda</a><script>
function ig(id){
document.getEle mentById(id).st yle.visibility = 'hidden';
}
ig('o22');
</script>
A posible problem is calling the function passing an object instead of an string:

<script>
ig('o22'); // Correct (passing an string)
ig(o22); // Bad (passing an object (variable))
</script>


Thank you! This example led me to fix the immediate problem. I had
tried passing the string to the function in double quotes and got a
syntax error. Your solution uses single quotes around the ID string
which I had not tried (I thought either was acceptable in Javascript
as long as they were not 'unbalanced"... ..

and now I am on to a new problem
Jul 23 '05 #8
Lee
Michael Winter said:

On 15 Oct 2004 07:36:05 -0700, Lee <RE************ **@cox.net> wrote:

[snip]
txtPhone and msgPhone are NOT the id's of any elements.


Actually, they are. Look closer at the contents of the table.


Ah, yes. They had wrapped.

I'll emphasize again though, that it's not appropriate to
use these id's when it's even simpler to pass references.

Jul 23 '05 #9
On 15 Oct 2004 09:28:56 -0700, JJA <jo***@cbmiweb. com> wrote:

[snip]
I had tried passing the string to the function in double quotes and got
a syntax error. Your solution uses single quotes around the ID string
which I had not tried (I thought either was acceptable in Javascript as
long as they were not 'unbalanced"... ..

and now I am on to a new problem


From your original post:

onSubmit="retur n validateTelnr ("txtPhone", "msgPhone", true);"

I missed this: the problem is your nested double quotes.

Whilst it is true that you can use either double or single quotes (I
prefer the latter for this very situation), you cannot nest quotes in
HTML. Had you validated your HTML (<URL:http://validator.w3.or g/>), you
would have discovered this.

There are two fixes:

1) Use single quotes in attribute values.
2) Use the &quot; character entity.

However, please read my other post in this thread (if you haven't already).

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #10

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

Similar topics

3
1634
by: cainlevy | last post by:
Something that's been bugging me for a while: I can't figure out how to register an object method as an event handler, and still use the 'this' keyword inside the handler to refer to the object. For example: function myObj () { this.toString = function(){return 'myObj'}; //define string representation of this object document.getElementById('test_tag_id').onclick = this.test; //attach to some clickable element
1
1912
by: DIZZIEDAZZ | last post by:
Is there a way, I could pass the reference to a pop up window to another function? Basically, this is what I want to var win= window.open("x.htm".....) SetValue(win,"txtName"); //------------------------------------------- function SetValue (win, ctlID)
14
3492
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src="" id="eventImage0" class="eventImage"><img src="" id="eventImage1" class="eventImage"></div>
2
2136
by: vunet.us | last post by:
Please, explain an interesting phenomenon, if you can. I have an array of references to an HTML element: <div id='container'> <div id='someId1'></div> <div id='someId2'></div> </div> ..... myArray = document.getElementById("someId1"); myArray = document.getElementById("someId2");
22
4188
by: Nehil | last post by:
Does C follow call by value convention or call by reference? i see that there is nothing like reference in C standard but it is referenced. still, what should be the answer for the above question?
1
17657
by: pingalkar | last post by:
Hi, In my application, I call one popup winodow by using this link.. <a href="#" onClick="return showWindow('1','XYZ');"> <img src="images/magnifier.gif" ALT="Chemicals" width=18 height=20 border=0> </a> In this showWindow function.... var newWindow = '';
5
2226
by: dwmartin18 | last post by:
Hello everyone. I have quite the puzzling problem with a script I have been working on lately. I have created a function that can be called to create a new html element (e.g. input, select, div, etc.). It is used as follows: addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1") The first argument is an ID of the location where the new element it to be appended. The second argument is the type...
11
3360
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible ways of passing an array. In the following code, fun1(int a1) - same as fun1(int* a1) - where both are of the type passed by reference. Inside this function, another pointer a1 is created whose address &a1 is different from that of the passed...
275
12379
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9568
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
9399
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,...
1
9957
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
8832
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
5276
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
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
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.