jquery通配符用于带有数组符号的复杂输入名称

标签 jquery

我有 text 类型的复杂输入元素,其名称如 product[1][combinations][x][price]。此元素有很多个,名称上的区别仅在于 [combinations][x] 后面的值。

例如:

product[1][price]
product[1][combinations][x][price]
product[1][combinations][xx][price]
product[1][combinations][xxx][price]
product[1][combinations][xxxx][price]

product[1][sale_price]
product[1][combinations][x][sale_price]
product[1][combinations][xx][sale_price]
product[1][combinations][xxx][sale_price]
product[1][combinations][xxxx][sale_price]

product[2][price]
product[2][combinations][a][price]
product[2][combinations][aa][price]
product[2][combinations][aaa][price]
product[2][combinations][aaaa][price]

product[2][sale_price]
product[2][combinations][a][sale_price]
product[2][combinations][aa][sale_price]
product[2][combinations][aaa][sale_price]
product[2][combinations][aaaa][sale_price]

上述值xxxxxxxxxxaaaaaaaaaa 表示每个product[id] 的唯一值。每个组中的第一个定义(例如product[2][sale_price])代表父产品或所有者产品,其值将批量更新到其子产品(组合)。

我想根据存储的信息类型(例如 sale_price)查找这些元素的组,然后更改其值。我不需要考虑唯一值,[x],所以我希望可以使用通配符。

我希望这样的事情能够解决问题(示例):

$("input[name='product[1][combinations][*][price]'][type='text']").val(0);

但是我猜 * 并不是真正的通配符,所以我不能那样使用它。

我意识到我可以做这样的事情,但这会将 0 分配给所有输入,而不仅仅是 sale_price:

$("input[name^='product[1][combinations]'][type='text']").val(0);

我如何替换这个($("input[name='product[1][combinations][*][price]'][type='text']").val(0); ) 选择器带有适当的通配符?如果可能的话,我希望保持名称数组值的顺序相同

最佳答案

不确定这是否是您想要的...但您可以使用带有 $ 的属性选择器,这会选择所有以指定文本结尾的输入...因此

$("input[name$='[price]']").val(0);
$("input[name$='[sale_price]']").val(1);

实际上你并不需要[type='text']上面的选择器将获取名称以字符串结尾的元素...但是如果你想更具体并且确保您只需要输入然后就可以了..您也可以在此处添加相同的内容。

example fiddle here

已更新

然后您可以使用多个属性选择器..^ 搜索以指定字符串开头的元素

$("input[name^='product[1]'][name$='[price]']").val(0);
$("input[name^='product[1]'][name$='[sale_price]']").val(1);

updated fiddle

关于jquery通配符用于带有数组符号的复杂输入名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618040/

相关文章:

javascript - Jquery改变鼠标悬停时div的背景颜色

Javascript 函数未触发且控制台未提供任何见解

javascript - jQuery事件绑定(bind)应用全身

jquery - 需要对图像的两侧应用 alpha 渐变

javascript - 使用 Ember.$.ajax() 发送具有关系的数据

jquery - 宽度适合 100% 不工作

javascript - 访问 $.each() 中的项目

javascript - 什么时候有一个函数在 $(document).ready()

javascript - jQuery 检查字符串是否包含单词

Javascript 函数返回 session 对象