GarryJones said:
I want to set the value of an input field with javascript but I do not
understand the syntax for this.
This example does not work. Once I fathom this out I will move on to
setting the value with the onlick property of a <td>, but first things
first...
<script type="text/javascript" >
testform.test1.value = "test"
This fails for two reasons:
1. You are assuming that the name or ID of an element makes the
corresponding DOM object automatically accessible by an equally named
property of an object in the scope chain. However, that is only the case
in the MSHTML DOM, and it is error-prone.
2. If we would assume that `testform' would refer to an HTMLInputElement
object representing the `input' element at some point of execution, at
*this* point that DOM object certainly certainly has not been created
yet because the `input' element has not been parsed yet.
Since `testform' therefore yields `undefined', further property access
to `testform.test1' results in throwing a ReferenceError exception:
"testform is not defined."
There are two ways to correct this:
a) Move the `script' element after the `input' element. However, that would
rely on the DOM object being created fast enough and while parsing,
instead of being available only after creation of the DOM tree has been
completed. So that is not recommended.
b) Use the standards-compliant and backwards-compatible intrinsic event
handler `onload' attribute:
<body
onload="document.forms['testform'].elements['test1'].value = 'test';">
In this case it will suffice. In other, more complicated cases, code should
be (virtually) outsourced into methods that are called from the event
listener code (that is created by the event handler attribute value), such as:
<body onload="setTest1('test');">
http://www.w3.org/TR/html401/interact/scripts.html#adef-onload
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents
<FORM action="dosomething.php" method="post" name="form1"
id="testform" >
<input name="scfchknum" type="text" id="test1" size="10" maxlength="7"
You may safely omit `type="text"'; "text" is the default value for this
attribute:
http://www.w3.org/TR/html401/interact/forms.html#h-17.4
</FORM>
Any help greatly appreciated.
Before continuing, you should be (pretty) sure that your markup is Valid:
http://validator.w3.org/
HTH
PointedEars