【问题标题】:How to access form input value in javascript with special characters in input name?如何使用输入名称中的特殊字符访问javascript中的表单输入值?
【发布时间】:2013-05-04 16:10:25
【问题描述】:

我有一个无法更改输入值字段名称的表单。 一个这样的字段在 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中的输入字段值?

【问题讨论】:

标签: javascript html forms variables input


【解决方案1】:

这行得通:

http://jsfiddle.net/mqv82/1/

<input type="text" name="var[list]" id="ixv[list]" value="foo">

alert(document.getElementById('ixv[list]').value);

【讨论】:

    【解决方案2】:

    试试这样:

    var x = document.getElementsByName("var[list]")[0].value;
    

    【讨论】:

    • 这将返回错误,document.getElementsByName 返回一个 HTMLCollection !
    【解决方案3】:

    在现代浏览器中,使用querySelectorAll

    document.querySelectorAll('[name="var[list]"]')[0].value 
    

    或者如果你知道 id 试试getElementById

    document.getElementById('ixv[list]').value 
    

    getElementsByName

    document.getElementsByName('var[list]')[0] .value 
    

    以上三个将返回相同的结果

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 2016-09-04
      相关资源
      最近更新 更多