Javascript form oddity

Soldato
Joined
18 Oct 2002
Posts
15,699
Location
The land of milk & beans
Hi all,

is there any reason the below code won't work...

Code:
var objTextArea = document.frmTest.txtMain
alert(objTextArea.value)
all i get is 'document.frmTest.txtMain is not an object'.

everything is typed correctly, and the form and field do exists as it works when i hard code document.frmTest.txtMain, but i need to parameterise it so i can reuse the code elsewhere.

Can someone help before i turn into a proper scopey :)

Cheers
 
Works perfectly fine as you have it:-

Code:
<html>
<head>
<script language="javascript">

function test()
{
var objTextArea = document.frmTest.txtMain
alert(objTextArea.value)
}

</script>

</head>

<body>

<form name = "frmTest">

<input type='button' onclick='javascript:test()'>

<input type='text' name='txtMain' id='txtMain'>

</form>

</body>

<html>

or if you have it as a string then:-

Code:
function test()
{
var testStr = "document.frmTest.txtMain"
var objTextArea = eval(testStr)
alert(objTextArea.value)
}
 
Last edited:
you're right it does work that way, although in my haste i forgot to mention a few things, first off the input is actually a textarea - not that it really makes any difference code wise.

second, the form object variable is global scope, so it's available to all functions (in theory anyway).

Here's some more code, although a bit more detailed this time....

Code:
	var szSelection = ""
	var szBegin
	var szEnd
	var szStartTag = ""
	var szEndTag = ""
	
	var objTextArea = document.frmTest.txtMain
		
	function addTag(szTagType) {	
		// DOES STUFF
		objTextArea.value = szResult
	}

	function xyz(szABC) {
		objTextArea.value += szSomethingElse
	}
the problem line is still where the global object variable is defined, it still says it's null or not an object, yet if i put it in the specific function it works :confused:
 
Last edited:
nmind - managed to fix it. you can't declare a variable to a form object as global in an external js file because the form hasn't been created when the js is initialised.

the fix is to call a function on body load to set your variables to the form fields.

:)
 
Back
Top Bottom