Reputation: 2140
I'm adding some javascript validation to a form. The form has fields that currently look like:
<input name="Employee Full Name" value="" type="text" id="Employee Full Name" size="30" maxlength="50" style="width:300px;">
I am trying to access the values of the fields, but I seem to be doing it incorrectly with the spaces in the input name, is there a way to escape?
if (theForm.Employee Full Name.value == ""){
alert("Please enter a value for the \"Employee Full Name\" field.");
theForm.Employee Full Name.focus();
return (false);
}
Upvotes: 0
Views: 2939
Reputation: 179046
You can use the bracket notation for objects as well as arrays:
theForm['Employee Full Name'].value == ""
This allows you to access attributes where the names are invalid in a .
notation syntax:
foo.1 //foo['1']
foo.this-is-wrong //foo['this-is-wrong']
foo.bar.baz //although this looks correct, it's wrong if you actually wanted foo['bar.baz']
Upvotes: 1
Reputation: 348972
Contain them within square braces, using quotes.
if (theForm["Employee Full Name"]value == ""){
alert("Please enter a value for the \"Employee Full Name\" field.");
theForm.["Employee Full Name"].focus();
return false;
}
Every JavaScript object can also be referenced in this way. For instance, all of the following methods have the same result:
window.location.href
window["location"].href
window.location["href"]
window["location"]['href'] //Single quotes / double quotes don't matter.
Upvotes: 1