PDA

View Full Version : How should I refer to form field in js


DamianWarS
07-06-2009, 10:45 AM
What is the best way for me to access a form field in JavaScript. Lets say for example I have a form with the name of "myForm" and I want to set the value of the first form field which is a textbox called "myTextBox" (both ID and Name) to "Hello World!"

document.myForm.myTextBox.value="Hello World!";
document.forms[0][0].value="Hello World!";
document.forms["myForm"]["myTextBox"].value="Hello World!";
document.getElementById("myTextBox").value="Hello World!";

or whatever other combination of the above you can have. If you have a better way of doing it then list that as well. Currently I am using the first example.

coothead
07-06-2009, 04:06 PM
Hi there DamianWarS,

it's a good job that you are using option 1 as the other three are not quite correct. :agree:
Of course, this may just be typing errors on your part but they should be...

document.forms[0][0].value="Hello World!"; /* no dot between forms and [0] */
document.forms["myForm"]["myTextBox"].value="Hello World!"; /* no dot between forms and ["myForm"]["myTextBox" */
document.getElementById("myTextBox").value="Hello World!";

I, personally prefer document.forms[0][0.value. ;)

DamianWarS
07-07-2009, 08:16 AM
yes they were just typing errors... this wasn't a test. Assuming that they were correct (which I have corrected already) which would be the best option

coothead
07-07-2009, 08:53 AM
Hi there DamianWarS,
...which would be the best option

I think that it is just personal preference, but I tend to use document.forms[0][0] mainly, and sometimes document.getElementById().