使用javascript访问HTML输入字段 - 输入名称中的空格

时间:2011-11-07 15:02:15

标签: javascript

我正在为表单添加一些javascript验证。表单目前的字段如下:

<input name="Employee Full Name" value="" type="text" id="Employee Full Name" size="30" maxlength="50" style="width:300px;">

我正在尝试访问字段的值,但我似乎是错误地使用输入名称中的空格,有没有办法逃脱?

if (theForm.Employee Full Name.value == ""){   
   alert("Please enter a value for the \"Employee Full Name\" field.");     
   theForm.Employee Full Name.focus();   
   return (false);   
}

2 个答案:

答案 0 :(得分:1)

使用引号将它们包含在方括号内。

if (theForm["Employee Full Name"]value == ""){   
   alert("Please enter a value for the \"Employee Full Name\" field.");     
   theForm.["Employee Full Name"].focus();   
   return false;
}

每个JavaScript对象也可以这种方式引用。例如,以下所有方法都具有相同的结果:

window.location.href
window["location"].href
window.location["href"]
window["location"]['href'] //Single quotes / double quotes don't matter.

答案 1 :(得分:1)

您可以对对象和数组使用括号表示法:

theForm['Employee Full Name'].value == ""

这允许您以.表示法语法访问名称无效的属性:

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']