我有一个表单,我无法更改输入值字段名称。 HTML中的一个这样的字段如下:
<body>
<form id="f" method="get" action="/code/submit.php">
<input type="text" name="var[list]" id="ixv[list]" value="">
<button type="button" title="Save" onclick="check();">
</form>
</body>
现在在我的javascript中,我想访问该输入值。 我尝试了这个,当然,因为[]看起来它不起作用 就像JS中的数组一样。
function check() {
var x=var[list].value;
alert(x);
}
问题是变量名称中包含[]。我怎样才能得到 javascript中的输入字段值?
答案 0 :(得分:2)
这有效:
<input type="text" name="var[list]" id="ixv[list]" value="foo">
alert(document.getElementById('ixv[list]').value);
答案 1 :(得分:1)
试试这样:
var x = document.getElementsByName("var[list]")[0].value;
答案 2 :(得分:0)
在现代浏览器中,使用querySelectorAll
document.querySelectorAll('[name="var[list]"]')[0].value
或者如果你知道id,请尝试getElementById
document.getElementById('ixv[list]').value
或getElementsByName
document.getElementsByName('var[list]')[0] .value
以上三个将返回相同的结果