Javascript in Content Page/Master Page setup

I  have some Javascript functions I was using in a standard asp.net page. I am now trying to use this script in a Content Page that references a Master page. In my script I am populating two variables with text from a couple of texboxes like this:

dblAverageSpeed = form1.txtAvs.value;
dblDistance = form1.txtDistance.value;

It's not working because I'm trying to reference the data from the textboxes with form1.txtAvs.value. There is no form1 because I'm now trying to do this inside a Content Page. My question is how do I get the value from my textboxes that are in my Content Page to be used in my script? Thanks!
myesterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rhythmluvrCommented:
I assume your using standard HTML textboxes. How come your not using asp.net textboxes?
0
LordOfPortsCommented:
Is your script within the same page? If yes, you can access the values using the getElementById function:

dblAverageSpeed = document.getElementById('txtAvs').value;
dblDistance = document.getElementById('txtDistance').value;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
myesterAuthor Commented:
Yes, I am using asp.net textboxes. I have attached the code for one of them. Can I still use the document.getElementById method?
<asp:TextBox ID="txtAvs" runat="server" onkeyup="calculateTime(); allow_numeric(this);" onkeydown="mykeyhandler()" 
                style="top: 145px; left: 250px; position: absolute; height: 22px; width: 65px"></asp:TextBox>

Open in new window

0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

myesterAuthor Commented:
LordOfPorts, I've altered my script with the document.getElementById method but now I've getting the Microsoft JScript runtime error: Object required. When I break this line is highlighted:

var strDistance = document.getElementById('txtDistance').value;

I've very new to all this so I really appreciate everyones help. Thanks!
0
LordOfPortsCommented:
Can you post more code, specifically the function where you declare the code above? document.getElementById function is for client side code, for server side code you should be able to reference the text box with txtDistance.Text, e.g.:

<script runat="server">
Sub calculateTime(sender As Object, e As EventArgs)
Label1.Text = "The distance is " & txtDistance.Text
End Sub
</script>
0
myesterAuthor Commented:
LordOfPorts, I have posted two of the functions I'm using. Thanks for your help.
function calculateAvs()
				{
				var strTime1 = document.getElementById('txtTime').value;
				if (strTime1.length > 7)
					{
					
						var strHours 
						var strTimeTemp
						var strMinutes
						var strAvsTemp
						var p_strMins = 0
						var p_strSecs = 0
						
						var strDistance = document.getElementById('txtDistance').value;
						//var strTime1 = form1.time.value;
						var strAvs //= form1.avs.value;
						
						strHours = parseInt(Mid(strTime1, 0, 2));
						//alert(strHours);
						p_strMins = parseInt(Mid(strTime1, 3, 2));
						p_strSecs = parseInt(Mid(strTime1, 6, 2));
                        strTimeTemp = (((strHours * 60) + (p_strMins) + (p_strSecs / 60)) / (60));
						strTime1 = FormatNumber(strTimeTemp,4,false,false,false);
						strAvsTemp = (strDistance / strTime1);
						//Formats the Average Speed
						strAvs = FormatNumber(strAvsTemp,2,false,false,false);
						document.getElementById('txtAvs').value = strAvs;
					}
				}
			function calculateTime() 
			{
					//These variables are for calculating the time when Avs and Distance are known
				var dblAverageSpeed //As Double
				var dblDistance //As Double
				var strTimeTemp1 //As Double
				var strFrac //As Single
				var sngMins1 //As Single
				var sngSecs1 //As Single
				var sngHoursTemp //As Single
				var intTimeConcat //As Integer
				var strIndex
				var strTime
				var strMins
				var strSecs
 
				var strDistance = document.getElementById('txtDistance').value;
				var strAvs = document.getElementById('txtAvs').value;
					
				if(isNaN( strAvs )== false) 
					{
					//alert("Please enter a numeric Value.");
					//}
					//else	
						if (strAvs.length > 1)
							{
////								dblAverageSpeed = form1.txtAvs.value;
////								dblDistance = form1.txtDistance.value;
								dblAverageSpeed = document.getElementById('txtAvs').value;
                                dblDistance = document.getElementById('txtDistance').value;
 
								//Used to calculate the Event time when Average Speed and distance are entered
								strTimeTemp1 = (1 / ((dblAverageSpeed) / (dblDistance)));
								//alert(strTimeTemp1);
								if ((strTimeTemp1) == parseInt(strTimeTemp1))
									{ 
									strHours = strTimeTemp1;
									strHours = new String(strHours)
									if (Len(strHours) == 1)
										{
										strHours = 0 + strHours;
										}
									intTimeConcat = strHours + "00" + "00"
									strTime = insertNthChar(intTimeConcat,':',2)
									form1.txtTime.value = strTime
									}
 
								if ((strTimeTemp1) != parseInt(strTimeTemp1)) 
									{
									strTimeTemp1 = new String(strTimeTemp1)
									strIndex = strTimeTemp1.indexOf(".")
									strFrac = strTimeTemp1.substr(strIndex)
									sngMins1 = strFrac * 60;
									strMins = parseInt(strFrac * 60);
									strMins = new String(strMins)
									if (Len(strMins) == 1) 
										{
										strMins = 0 + strMins
										}
									if ((sngMins1) != (parseInt(strMins))) 
										{
										sngMins1 = new String(sngMins1)
										strIndex = sngMins1.indexOf(".")
										sngSecs1 = sngMins1.substr(strIndex)
										strSecs = parseInt(sngSecs1 * 60);
										strSecs = new String(strSecs)
										}
									else
										strSecs = "00";
							
									if ((Len(strSecs) == 1))
										{
										strSecs = (0 + strSecs);
										}
									sngHoursTemp = strTimeTemp1.substr(0, 2);
									sngHoursTemp = new String(sngHoursTemp)
									//if(isNaN( strAvs )== false)
										//{
										rExp = /\./gi;
										strHours = sngHoursTemp.replace(rExp,'')
										//}
									if (Len(strHours) == 1)
										{
										strHours = new String(strHours)
										strHours = 0 + strHours;
										}
																		
									intTimeConcat = strHours + strMins + strSecs;
									strTime = insertNthChar(intTimeConcat,':',2)
									document.getElementById('txtTime').value = strTime;	
	
									}
								
							}
					}
				}
		</script>

Open in new window

0
LordOfPortsCommented:
The getElementById function should work properly since this appears to be client side code. Just to double-check you have the script declaration something like:

...
<head>
<script language="javascript" type="text/javascript">
// your code specified above
</script>
</head>
...


then in between the <body></body> tags you have the txtAvs, txtDescription, and txtTime text boxes something like:

<asp:TextBox ID="txtDescription" runat="server" style="top: 145px; left: 250px; position: absolute; height: 22px; width: 65px"></asp:TextBox>

<asp:TextBox ID="txtTime" runat="server" style="top: 145px; left: 250px; position: absolute; height: 22px; width: 65px"></asp:TextBox>

<asp:TextBox ID="txtAvs" runat="server" onkeyup="calculateTime(); allow_numeric(this);" onkeydown="mykeyhandler()" style="top: 145px; left: 250px; position: absolute; height: 22px; width: 65px"></asp:TextBox>

correct?
0
myesterAuthor Commented:
LordOfPorts, Yes I have the declaration right. The difference is that all this code is inside a Content Page so there are no <head> or <body> tags. All the code is inside the Content area of the Content Page. I've attached the code from the entire page. The function allow_numeric(obj) function is working for the txtDistance txtbox. It's the functions that try to use the values from the txtboxes that are not working. Again, thanks for all your help.
<%@ Page Language="VB" MasterPageFile="~/Default.master" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" title="Untitled Page" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type= "text/javascript">
			function allow_numeric(obj){
				if (!/^\d+(\.\d*)?$/.test(obj.value)){
					obj.value= theVal = obj.value.replace(/[^0-9.]/g,'');
					if(theVal>""){
					obj.value=parseFloat("0"+theVal);
					obj.focus()
					}
				}
			}
			
			function mykeyhandler() {
				if (window.event && window.event.keyCode == 8) {
					document.getElementById('txtTime').value = ''
				    document.getElementById('txtAvs').value = ''
					//window.event.cancelBubble = true;
					//window.event.returnValue = false;
					return false;
				}
			}
 
			function insertNthChar(string,chr,nth) {
				var output = '';
				for (var i=0; i<string.length; i++) {
					if (i>0 && i%2 == 0)
					output += chr;
					output += string.charAt(i);
				}
 
				return output;
				}
 
     		function Len(str)
				/***
						IN: str - the string whose length we are interested in
						RETVAL: The number of characters in the string
				***/
				{  return String(str).length;  }
		
			function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
				/**********************************************************************
					IN:
						NUM - the number to format
						decimalNum - the number of decimal places to format the number to
						bolLeadingZero - true / false - display a leading zero for
														numbers between -1 and 1
						bolParens - true / false - use parenthesis around negative numbers
						bolCommas - put commas as number separators.
				 
					RETVAL:
						The formatted number!
				**********************************************************************/
				{ 
						if (isNaN(parseInt(num))) return "NaN";
 
					var tmpNum = num;
					var iSign = num < 0 ? -1 : 1;		// Get sign of number
					
					// Adjust number so only the specified number of numbers after
					// the decimal point are shown.
					tmpNum *= Math.pow(10,decimalNum);
					tmpNum = Math.round(Math.abs(tmpNum))
					tmpNum /= Math.pow(10,decimalNum);
					tmpNum *= iSign;					// Readjust for sign
				
					// Create a string object to do our formatting on
					var tmpNumStr = new String(tmpNum);
 
					// See if we need to strip out the leading zero or not.
					if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
						if (num > 0)
							tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
						else
							tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
						
					// See if we need to put in the commas
					if (bolCommas && (num >= 1000 || num <= -1000)) {
						var iStart = tmpNumStr.indexOf(".");
						if (iStart < 0)
							iStart = tmpNumStr.length;
 
						iStart -= 3;
						while (iStart >= 1) {
							tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
							iStart -= 3;
						}		
					}
 
					// See if we need to use parenthesis
					if (bolParens && num < 0)
						tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
 
					return tmpNumStr;		// Return our formatted string!
				}
 
			function Mid(str, start, len)
				/***
						IN: str - the string we are LEFTing
							start - our string's starting position (0 based!!)
							len - how many characters from start we want to get
						RETVAL: The substring from start to start+len
				***/
				{
						// Make sure start and len are within proper bounds
						if (start < 0 || len < 0) return "";
 
						var iEnd, iLen = String(str).length;
						if (start + len > iLen)
								iEnd = iLen;
						else
								iEnd = start + len;
 
						return String(str).substring(start,iEnd);
				}
		
			function calculateAvs()
				{
				var strTime1 = document.getElementById('txtTime').value;
				if (strTime1.length > 7)
					{
					
						var strHours 
						var strTimeTemp
						var strMinutes
						var strAvsTemp
						var p_strMins = 0
						var p_strSecs = 0
						
						var strDistance = document.getElementById('txtDistance').value;
						//var strTime1 = form1.time.value;
						var strAvs //= form1.avs.value;
						
						strHours = parseInt(Mid(strTime1, 0, 2));
						//alert(strHours);
						p_strMins = parseInt(Mid(strTime1, 3, 2));
						p_strSecs = parseInt(Mid(strTime1, 6, 2));
                        strTimeTemp = (((strHours * 60) + (p_strMins) + (p_strSecs / 60)) / (60));
						strTime1 = FormatNumber(strTimeTemp,4,false,false,false);
						strAvsTemp = (strDistance / strTime1);
						//Formats the Average Speed
						strAvs = FormatNumber(strAvsTemp,2,false,false,false);
						document.getElementById('txtAvs').value = strAvs;
					}
				}
			function calculateTime() 
			{
					//These variables are for calculating the time when Avs and Distance are known
				var dblAverageSpeed //As Double
				var dblDistance //As Double
				var strTimeTemp1 //As Double
				var strFrac //As Single
				var sngMins1 //As Single
				var sngSecs1 //As Single
				var sngHoursTemp //As Single
				var intTimeConcat //As Integer
				var strIndex
				var strTime
				var strMins
				var strSecs
 
				var strDistance = document.getElementById('txtDistance').value;
				var strAvs = document.getElementById('txtAvs').value;
					
				if(isNaN( strAvs )== false) 
					{
					//alert("Please enter a numeric Value.");
					//}
					//else	
						if (strAvs.length > 1)
							{
////								dblAverageSpeed = form1.txtAvs.value;
////								dblDistance = form1.txtDistance.value;
								dblAverageSpeed = document.getElementById('txtAvs').value;
                                dblDistance = document.getElementById('txtDistance').value;
 
								//Used to calculate the Event time when Average Speed and distance are entered
								strTimeTemp1 = (1 / ((dblAverageSpeed) / (dblDistance)));
								//alert(strTimeTemp1);
								if ((strTimeTemp1) == parseInt(strTimeTemp1))
									{ 
									strHours = strTimeTemp1;
									strHours = new String(strHours)
									if (Len(strHours) == 1)
										{
										strHours = 0 + strHours;
										}
									intTimeConcat = strHours + "00" + "00"
									strTime = insertNthChar(intTimeConcat,':',2)
									document.getElementById('txtTime').value = strTime
									}
 
								if ((strTimeTemp1) != parseInt(strTimeTemp1)) 
									{
									strTimeTemp1 = new String(strTimeTemp1)
									strIndex = strTimeTemp1.indexOf(".")
									strFrac = strTimeTemp1.substr(strIndex)
									sngMins1 = strFrac * 60;
									strMins = parseInt(strFrac * 60);
									strMins = new String(strMins)
									if (Len(strMins) == 1) 
										{
										strMins = 0 + strMins
										}
									if ((sngMins1) != (parseInt(strMins))) 
										{
										sngMins1 = new String(sngMins1)
										strIndex = sngMins1.indexOf(".")
										sngSecs1 = sngMins1.substr(strIndex)
										strSecs = parseInt(sngSecs1 * 60);
										strSecs = new String(strSecs)
										}
									else
										strSecs = "00";
							
									if ((Len(strSecs) == 1))
										{
										strSecs = (0 + strSecs);
										}
									sngHoursTemp = strTimeTemp1.substr(0, 2);
									sngHoursTemp = new String(sngHoursTemp)
									//if(isNaN( strAvs )== false)
										//{
										rExp = /\./gi;
										strHours = sngHoursTemp.replace(rExp,'')
										//}
									if (Len(strHours) == 1)
										{
										strHours = new String(strHours)
										strHours = 0 + strHours;
										}
																		
									intTimeConcat = strHours + strMins + strSecs;
									strTime = insertNthChar(intTimeConcat,':',2)
									document.getElementById('txtTime').value = strTime;	
	
									}
								
							}
					}
				}
		</script>
		<script type="text/javascript"> /*This script formats the txtTime box as you're are typing to format hh:mm:ss*/
			var fmt=true;
			function chk(k){
			if(document.all){k=k.keyCode;}else{k=k.which;}
			if(!((k>=48 && k<=57) || k==58)){return false;}
			}
 
			function frmat(obj){
			var nw=obj.value.split(':').join('');
			if(nw.length>2&&nw.length<=4){nw=nw.substring(0,2)+':'+nw.substring(2,nw.length);}
			else if(nw.length>4){nw=nw.substring(0,2)+':'+nw.substring(2,4)+':'+nw.substring(4,nw/length);}
			obj.value=nw;
				if(parseInt(nw.substr(3,2))>59){
				alert('Minutes Can\'t exceed 59')
				}
				if(parseInt(nw.substr(6,2))>59){
				nw = nw.substring(0,6)
				obj.value=nw;
				alert('Seconds Can\'t exceed 59')
				}
			}
		</script>
<div id="body">
    
<asp:Panel ID="Panel1" runat="server" style="top: 32px; left: 133px; position: absolute; height: 430px; width: 450px">
       
            <a href="http://www.zapatec.com/website/main/products/prod1/"></a>
 
            <asp:DropDownList ID="ddlRideType" runat="server" 
                
                style="top: 80px; left: 70px; position: absolute; height: 24px; width: 132px" 
                DataSourceID="SqlDataSource1" DataTextField="EventType" 
                DataValueField="EventType">
            </asp:DropDownList>
            <asp:TextBox ID="txtDistance" runat="server" onkeyup="allow_numeric(this);" 
                style="top: 145px; left: 70px; position: absolute; height: 22px; width: 65px"></asp:TextBox>
            <asp:TextBox ID="txtTime" onkeypress="return chk(event);" onkeyup="frmat(this); calculateAvs();"
				onkeydown="mykeyhandler();" runat="server" 
                style="top: 145px; left: 160px; position: absolute; height: 22px; width: 65px" MaxLength="8"></asp:TextBox>
            <asp:TextBox ID="txtAvs" runat="server" onkeyup="calculateTime(); allow_numeric(this);" onkeydown="mykeyhandler()" 
                style="top: 145px; left: 250px; position: absolute; height: 22px; width: 65px"></asp:TextBox>           
            <asp:TextBox ID="txtRoute" runat="server" 
                style="top: 210px; left: 70px; position: absolute; height: 50px; width: 285px"></asp:TextBox>
            <asp:TextBox ID="txtMemo" runat="server" 
                
                style="top: 310px; left: 70px; position: absolute; height: 50px; width: 285px"></asp:TextBox>
            <asp:Button ID="btnAddRide" runat="server" 
                style="top: 390px; left: 75px; position: absolute; height: 26px; width: 195px" 
                Text="Add Ride" />
            <asp:Label ID="Label3" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 70px; position: absolute; top: 60px" 
                Text="Ride Type"></asp:Label>
            <asp:Label ID="Label4" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 225px; position: absolute; top: 60px" Text="Date"></asp:Label>
            <asp:Label ID="Label5" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 70px; position: absolute; top: 125px" 
                Text="Distance"></asp:Label>
            <asp:Label ID="Label6" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 160px; position: absolute; top: 125px" Text="Time"></asp:Label>
            <asp:Label ID="Label7" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 250px; position: absolute; top: 125px" Text="Avs"></asp:Label>
            <asp:Label ID="Label8" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 70px; position: absolute; top: 190px" Text="Route"></asp:Label>
            <asp:Label ID="Label9" runat="server" Font-Bold="True" 
                Style="z-index: 106; left: 70px; position: absolute; top: 290px" Text="Memo"></asp:Label>
            <asp:Label ID="Label1" runat="server" BackColor="#000066" Font-Bold="True" 
                Font-Size="X-Large" ForeColor="White" 
                Style="z-index: 100; left: 0px; position: absolute; top: 0px; text-align: center; height: 46px; width: 450px;" 
                Text="Add Ride"></asp:Label>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:CyclistJournalDB %>" 
                SelectCommand="SELECT [EventType] FROM [RideType]"></asp:SqlDataSource>
           <noscript>
<br/>
            This page uses a <a href="http://www.zapatec.com/website/main/products/prod1/"> 
            Javascript Calendar </a>, but your browser does not support Javascript. 
<br/>
            Either enable Javascript in your Browser or upgrade to a newer version.
</noscript>
 
        </asp:Panel>
    
        <asp:Panel ID="Panel2" runat="server" 
            
            
        style="top: 540px; left: 35px; position: absolute; height: 29px; width: 388px">
            <br><a href="http://www.zapatec.com/website/main/products/prod1/">Zapatec 
            Javascript Calendar</a><br>
        </asp:Panel>
</div>
 
</asp:Content>

Open in new window

0
LordOfPortsCommented:
Let's try this, run the page in the browser, then view the page source and find the text box for distance and write down the client side ID of the text box; then replace the txtDistance in document.getElementById('txtDistance').value with the id generated on the client side. There is also a very useful post at http://forums.asp.net/p/1038768/1441122.aspx but just to confirm this is the same issue try the steps above.
0
myesterAuthor Commented:
LordOfPorts I replaced the textbox names with ctl00_ContentPlaceHolder1_txtDistance and with your help from your original answer this now works just like it's suppose to. Thanks for all your help and expertise for a hobbist who really enjoys this.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.