javascript troubleshooting

M

MattB

I'm just trying to do some simple javascript in a form to convert Lbs in
one textbox to kg in another. I'm doing the following inside a If Not
IsPostBack block:

Dim strLbs2kg As String
strLbs2kg = "<script language='javascript'> " & _
"function Lbs2kg() " & _
"{" & _
"var Lbs = 0; " & _
"Lbs = " & txtWeight.ClientID & ".value; " & _
txtWeight_m.ClientID & ".value = Lbs*0.454; " & _
"}" & _
"</script>"
Page.RegisterClientScriptBlock("Lbs2kg", strLbs2kg)
txtWeight.Attributes.Add("onChange", "Lbs2kg()")

But when I type into my txtWeight box and tab off, the kg field is not
populated and I get an script error in the browser saying:

Error: 'txtWeight' is undefined
Code: 0

I thought the ClientID were automatically generated. Id that not true?
Any hints on making this work? Thanks!

Matt
 
C

Chris Botha

The ClientID is only valid in the code-behind, so you must declare a
variable up top in your class that can be accessed from the Java script,
like
Protected m_TextWeightClntId as String
then in your page load, do
m_TextWeightClntId = TextWeight.ClientID
then to get hold of it in the Java script
var theTxtBox = document.GetElementById("<%=m_TextWeightClntId%>");
 
B

Bruce Barker

your code looks correct. is txtWeight visible? if not, it won't render and
the client code will fail. if its not visible switch to a hidden field.

-- bruce (sqlwork.com)
 
C

Chris Botha

Oops, sorry, you are building the Java script in the code-behind, so it will
have the right ID, ignore my message above.
The Java script will not find the boxes though, do it like
"Lbs = Form1." & txtWeight.ClientID & ".value; ......
thus put a "Form1." in front.
 

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,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top