Why are labels handled differently than an input control with clie

G

Guest

Here is the rendered output from my page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>Untitled Page</title></head>
<body>
<form name="aspnetForm" method="post" action="child.aspx" id="aspnetForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUKMTAzNzI3NDIwMGRkZWiDaQtY8r7RUqQI1w/SRH9RC8k=" />
</div>
<div>
<div>
<label id="ctl00_ph_lbl">label</label>
<input name="ctl00$ph$txt" type="text" id="ctl00_ph_txt"
value="textbox" />
<button id="ctl00_ph_btn" onclick="test()" value="abcdefg">
</button>
</div>

<script type="text/javascript" language="javascript">
function test(){
alert(ctl00_ph_lbl.innerText);
alert(document.aspnetForm.ctl00_ph_txt.value);
}
</script>
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION"
id="__EVENTVALIDATION"
value="/wEWAgLYyMeTBwLaocbcB+Tmua4QHW6PavIEFZo2N7QLNNk9" />
</div>
</form>
</body>
</html>

In the javascript, how come I have to add "document.aspnetForm" before the
clientId code on the input control but not on the label control? If I omit
"document.aspnetForm" from the alert line for the input control, I get the
error message "ctl00_ph_txt is undefined". Is there some definition of when
a control needs this and when it doesn't?
 
M

MatsL

I'm not 100% sure but I think only <input /> controls are added to the
form's control collection (on the client, that is), so the label is
located in the document and the textbox in the form.
You are usually better of getting a reference to the control with
javascript by using the getElementByID() function.
Then you can just do getElementByID('ctl00_ph_lbl').innerText and
getElementByID('ctl00_ph_txt').value.

Consistent and nice =)

//Mats
 
G

Guest

That's incorrect. Both the controls are in the forms Controls collection.

I don't want to hard code the clientId ("ctl00_ph_txt") into the javascript
because if the control was moved into another container object, the id
would then be wrong. However, in this case, using
getElementByID('ctl00_ph_txt')
as a test does not solve the problem, it still can't get a reference to the
control.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top