简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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