If your script is in the head of the document, then it’s running before the form elements in the body even exist. Place the script at the end of the body, just before the </body> tag.
On a similar subject, the below script clears the value of text input if the value is set to it’s corresponding array key.
The problem seems to be here: examplearray[id]. Is it possible to use the id argument when it’s value is this? Or does it have to take the name attribute as a string?
Thanks in advance.
var examplearray = {};
examplearray.example1 = "A";
examplearray.example2 = "B";
examplearray.example3 = "C";
<input type="text" name="example1" onFocus="clear_textbox(this)"/>
function clear_textbox(id)
{
if (id.value == examplearray[id])
id.value = "";
}
The value being passed to the function is not an id string, instead it’s a reference to the element itself so it really should be called el instead of id for the function argument.
You can then use el.name to get the array reference.
function clear_textbox(el)
{
if (el.value == examplearray[el.name]) {
el.value = "";
}
}
If it was the example1 field that was clicked on, then yes, it would refer to document.frm.example1
In terms of what the this keyword literally equals, it’s better to think of it as being the actual element that fired off the event, the one on which the onclick attribute is attached.
References such as the this keyword, document.frm.example1, and even
document.getElementsByName(‘frm’)[0].elements[‘example1’] are all just ways of getting you to the element that’s on the page.