2013-05-17 26 views
5

我有text類型的複雜輸入元素,其名稱爲product[1][combinations][x][price]。這個元素有很多,名稱只有在[combinations]之後和[x]之後的值不同。帶有數組符號的複雜輸入名稱的jquery通配符

例如:

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] 

上述值xxxxxxxxxxaaaaaaaaaaproduct[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);)選擇?我想,如果能夠保持名稱數組值以相同的順序

回答

5

不知道這是你想要的...但是你可以使用屬性selecter與$這個選擇所有與指定的文本結尾的投入......所以這將是

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

和你實際上並不需要[type='text']上面的選擇器將得到名稱以字符串結尾的元素......但是如果你想更具體一些,並確保你只需要輸入,那麼它的罰款......你可以在這裏添加相同的太。

example fiddle here

更新

那麼您可以使用多個屬性選擇.. ^搜索的元素用指定的字符串begining

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

updated fiddle

+0

幾乎認爲這會爲我做...除了在定位名稱的END時,您將失去產品[1]選擇器,用於限制哪些值將更新(每個產品) – binnyb

+0

@binnyb更新..請檢查 – bipen

+1

是的謝謝就是這樣,undefined擊敗你雖然。 – binnyb