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

J

JJA

I'm trying to use document.getElementByID 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="UserProfileMaint.htm"
onSubmit="return validateTelnr ("txtPhone", "msgPhone", true);">
<p>&nbsp;</p>
<p>&nbsp;</p>
<table id="tblMain" border="0" width="100%">
<tr>
<td width="25%">&nbsp;</td>
<td width="25%">Phone</td>
<td width="25%"><input type="text" name="txtPhone" id="txtPhone"
size="20"></td>
<td width="25%"><input 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.getElementById)
return true; // not available on this browser - leave validation
to the server

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

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

RobG

JJA said:
I'm trying to use document.getElementByID inside a function where the [snip]
<td width="25%">&nbsp;</td>
<td width="25%">Phone</td>
<td width="25%"><input type="text" name="txtPhone" id="txtPhone"
size="20"></td>
<td width="25%"><input 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.
 
R

RobG

JJA wrote:

[snip]
onSubmit="return 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.getElementById(ifld); // this will fail on next
// stmt
//var elem = document.getElementById("txtPhone"); //COMMENTED OUT:
//this works
if (!elem.firstChild) //------> 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.
 
E

Eloi de San Mart?n Lagranje

There is no problem of using getElementById whith passed arguments, try this:
<a id="o22" href="#">asda</a><script>
function ig(id){
document.getElementById(id).style.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>
 
M

Michael Winter

I'm trying to use document.getElementByID 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.firstChild)
return true;
if (elem.firstChild.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
 
L

Lee

JJA said:
I'm trying to use document.getElementByID 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="UserProfileMaint.htm"
onSubmit="return 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="return validateTelnr(txtPhone, 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.test(vfld.value)) {
...
}
 
L

Lee

Michael Winter said:
[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.
 
J

JJA

There is no problem of using getElementById whith passed arguments, try this:
<a id="o22" href="#">asda</a><script>
function ig(id){
document.getElementById(id).style.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
 
M

Michael Winter

[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="return 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.org/>), 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
 
D

DGre

JJA said:
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

If you submit your code as working examples rather than snippets, it is
much simpler to debug. With snippets, we can only user our eyes and
brains rather than debuggers and validators.

Cheers, DG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top