javascript - 如何使用数值数组作为表单输入名称?

标签 javascript jquery html

<分区>

查看了很多关于此的问题 - 但找不到真正的答案。所以这里...

我有一个表单,我将在其中动态添加部分(在本例中为“与会者信息”),因此我想使用像 firstName[0]firstName[1] 这样的名称 等。我已经编写了代码来为每个部分添加一个新的数字索引。

然而...

当我尝试使用 JQuery(或纯 JS)读取任何表单字段(动态创建或非动态创建)的值时,我得到了未定义。如果我将名称更改为 firstName1firstName2 等,它会起作用。仅当我使用数字数组索引时.. nada.

我试过...

$('#firstName[' + indexNum + ']')val();
$('input[name=firstName[' + indexNum + ']]').val();

.. 以及其他一些事情。 (是的,ID 与名称相同。)

有什么我想念的吗?

最佳答案

参见 Category:Attribute

Attribute values in selector expressions must follow the rules for W3C CSS selectors; in general, that means anything other than a valid identifier should be surrounded by quotation marks.

  • double quotes inside single quotes: $('a[rel="nofollow self"]')
  • single quotes inside double quotes: $("a[rel='nofollow self']")
  • escaped single quotes inside single quotes: $('a[rel=\'nofollowself\']')
  • escaped double quotes inside double quotes: $("a[rel=\"nofollow self\"]")

The variation you choose is generally a matter of style or convenience.


尝试将属性值用单引号括起来 'firstName["+ indexNum + "]'

var indexNum = 0;

console.log($("input[name='firstName[" + indexNum + "]']").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="firstName[0]" value="abc" />

或者使用两个反斜杠 \\ 字符转义 [] 字符

var indexNum = 0;

console.log($("input[name=firstName\\[" + indexNum + "\\]]").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="firstName[0]" value="abc" />

关于javascript - 如何使用数值数组作为表单输入名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139788/

相关文章:

javascript - 选择多个元素,其中一个元素是 $(this)

html - 将 flex 元素定位在最后一行或特定行

javascript - 将 Google 自动完成功能添加到 Google 搜索栏?

javascript - 在 JavaScript 正则表达式中放置变量

javascript - 如何不在 IE 中加载脚本?

html - 页眉和页脚之间的内容 100% 高度

html - 拉伸(stretch)输入[类型 ="text"] 以填充空间

javascript - Handlebars 模板中的 js 事件

jquery - 如何用jquery检测键盘组合?

javascript - 如何将元素传递给函数