">'); win.document.writeln(''); win.document.writeln(''); }
 

The Indefinite Article.

Sunday, February 27, 2005

Square Bracket Notation

One of the JavaScript things that was troubling me was how to refer to objects through a variable. This is useful if you want to programically say do this to that, but don't want to refer directly to this and that within a script.

function putFormVar(formName, inputName, inputValue){

myForm = document[formName];
myFormElem = myForm[inputName];
myFormElem.value = inputValue
}

So I want to set the value of an element within a form to be something, but I don't want to write in the name of the form and the name of the element within the script. I can't just write "myForm = document.formName" because the script will literally look for a form on the document called "formName." (As an aside, I wonder when putting a period or other punctuation outside of quote marks will become acceptable, because when I meant "formName" but I had to write "formName." because of the whole "don't-put-periods-after-quotes thing. I guess I could have wrote it ". . . a form called 'formName' on the document.") In this case, I want it to look for something set in the variable called formName so if the invocation of the function was "putFormVar("myPrettyForm", "theFantasticInput", "mostDeliciousVariable");" the form it looks for is document.myPrettyForm. The way of doing this is using bracket notation instead of dot notation. If the var formName is set to myPrettyForm, then you can refer to that form as document[formName] instead of referring to it directly as document.myPrettyForm. It took me a while to figure this out. I figured it out reading this page: Square Bracket Notation

0 Comments:

Post a Comment

<< Home