我有一个表单,并为其添加动态字段。添加字段后,我想以这样的方式增强name属性:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="evening" name="form-0-Day">
<input type="hidden" value="3" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
</form>
变为:
<form id="workshops" action="" method="post">
<input type="hidden" value="1" name="form-0-Workshops">
<input type="hidden" value="morning" name="form-0-Day">
<input type="hidden" value="3" name="form-1-Workshops">
<input type="hidden" value="evening" name="form-1-Day">
<input type="hidden" value="3" name="form-2-Workshops">
<input type="hidden" value="morning" name="form-2-Day">
</form>
我有这个开始,但我没有取得任何进展.....
var forms = $('form#workshops input[name$="Workshops"]');
for (var i=0, formCount=forms.length; i<formCount; i++){
$('form#workshops input[name$="Workshops"]').each(function() {
//$(this) seems to be empty
});
}
答案 0 :(得分:1)
尝试使用:
// Get all the forms inputs
var $forms = $('form#workshops input[name$="Workshops"]');
// Loop through each form inputs
$forms.each(function () {
console.log($(this));
});
答案 1 :(得分:0)
也许只是尝试:
$('#workshops input[name$="Workshops"]').each(function() { /*...*/ });
答案 2 :(得分:0)
您的代码会不断重新选择循环内部的内容。没有意义。
使用每个优势,它为您提供索引,因此无需执行for循环。 。
function rename (i) {
var parts = this.name.split("-");
parts[1] = i;
this.name = parts.join("-");
}
var form = $("#workshops");
form.find('input[name$="Workshops"]').each(rename);
form.find('input[name$="Day"]').each(rename);
答案 3 :(得分:0)
请尝试以下代码:
var forms_input = $('form#workshops input[name *="Workshops"]');
forms_input.each(function() {
console.log($(this))
});