我需要更改输入密钥名称(此密钥名称是动态的),如name="field[value][status]"
,如name="field[my_new_value][status]"
,并保持值状态,名称,年龄等......
var all_fields = $('[data-fields]');
var some_field = $(all_fields[2]).find('[name]');
// some_field[0] => fieldname[][status]
// some_field[1] => fieldname[][name]
// some_field[2] => fieldname[][age]
var field_dinamyc = $(all_fields[3]).find('[name]');
// field_dinamyc[0] => fieldname[dynamic_key][status]
// field_dinamyc[1] => fieldname[dynamic_key][name]
// field_dinamyc[2] => fieldname[dynamic_key][age]
console.log(some_field);
console.log(field_dinamyc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-fields>
<input type="text" name="fieldname[1][status]" value="status field 1" />
<input type="text" name="fieldname[1][name]" value="name field 1" />
<input type="text" name="fieldname[1][age]" value="age field 1" />
</div>
<div data-fields>
<input type="text" name="fieldname[2][status]" value="status field 2" />
<input type="text" name="fieldname[2][name]" value="name field 2" />
<input type="text" name="fieldname[2][age]" value="age field 2" />
</div>
<div data-fields>
<input type="text" name="fieldname[][status]" value="status field no key id" />
<input type="text" name="fieldname[][name]" value="name field no key id" />
<input type="text" name="fieldname[][age]" value="age field no key id" />
</div>
<div data-fields>
<input type="text" name="fieldname[dynamic_key][status]" value="status field any" />
<input type="text" name="fieldname[dynamic_key][name]" value="name field any" />
<input type="text" name="fieldname[dynamic_key][age]" value="age field any" />
</div>
答案 0 :(得分:1)
如果要将每个组的第一个数组名称覆盖到列表中的组的数字ID,您可以使用:
$('[data-fields]').each(function(i, fields){
// Loop over data-fields groups and grab their index
$('input', fields).each(function(){
// Rename first array value from name to group index
$(this).attr('name', $(this).attr('name').replace(/e\[[^\]]*\]/, 'e['+(i+1)+']'));
});
});