简体   繁体   English

以形式增强名称属性

[英]enhance name attribute in a form

I have a form, and add dynamically fields to it. 我有一个表单,并向其中动态添加字段。 After adding the fields I want to enhance the name attribute in the way that this: 添加字段后,我想以这种方式增强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>

Becomes: 成为:

<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>

I have this to start with but I don't make any progress..... 我首先要这样做,但是我没有任何进展。

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    
    });
}

Try using this: 尝试使用此:

// Get all the forms inputs
var $forms = $('form#workshops input[name$="Workshops"]');

// Loop through each form inputs
$forms.each(function () {
    console.log($(this));
});

也许只是尝试:

$('#workshops input[name$="Workshops"]').each(function() { /*...*/ });

Your code keeps re-selecting things inside of a loop. 您的代码不断在循环内重新选择事物。 Makes no sense. 没有意义。

Use each to your advantage, it gives you the index so there is no need to do the for loop. 充分利用每个优点,它会为您提供索引,因此无需进行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);

Please try the following code: 请尝试以下代码:

var forms_input = $('form#workshops input[name *="Workshops"]');

forms_input.each(function() {
    console.log($(this))
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM