添加具有动态字段名称的新字段将字段名称设置为相同的名称 [英] Adding new fields with dynamic field name sets field names to the same name

查看:164
本文介绍了添加具有动态字段名称的新字段将字段名称设置为相同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a div that contains a field which I want to add to the page when I click the add button.

我有一个包含一个字段的div,当我点击添加按钮时, //包含字段的div
< div class =dependent-rowstyle =visibility:hidden;>
< div class =rowstyle =border:1px solid #ccc; padding:5px; margin:10px 0;>
< label>名字< / label>
< input type =textvalue =class =firstName dependentfield>
< / div>
< / div>

// the div that contains the field <div class="dependent-row" style="visibility: hidden;"> <div class="row" style="border:1px solid #ccc; padding: 5px; margin: 10px 0;"> <label>First Name</label> <input type="text" value="" class="firstName dependentfield"> </div> </div>

每次点击添加按钮时都会显示一组新的字段。

A new set of fields display each time you click the add button.

我遇到的问题是它将所有添加的字段设置为同名。

The problem I am having is it sets all the added fields with the same name.

var index = 0;

$("#add-dependent-btn").on('click', function(e) {
    e.preventDefault();
    index++;

    $(this).after($('.dependent-row').html());
    $('.firstName').attr('name', 'fields[dependents][new'+index+'][fields][firstName]');
});

我知道我只需要在点击添加时添加的字段按钮,但无法弄清楚如何做到这一点。

I know I need to zero in on just the field I am adding at the time I clicked the add button but can not figure out how to do that.

如果我点击添加按钮两次,这里是呈现的html:

If I click the add button twice, here is the rendered html:

<input type="text" value="" class="firstName dependentfield" name="fields[dependents][new2][fields][firstName]">

<input type="text" value="" class="firstName dependentfield" name="fields[dependents][new2][fields][firstName]">


推荐答案

这基本上就是您如何做到的。

This is basically how you do it.

var rowObject = null;

function addRow(lineNumber) {
  if (rowObject != null) {
    var newRowObject = rowObject.clone();
    var label = "Label " + lineNumber;
    var inputName = 'fields[dependents][new' + lineNumber + '][fields][firstName]';

    var myLabel = newRowObject.find('label');
    myLabel.text(label);

    var myInput = newRowObject.find('input.firstName.dependentfield');
    myInput.val('');
    myInput.attr('name', inputName);

    $('div.dependent-row').append(newRowObject);
  }
}

$(function() {
  rowObject = $('div.dependent-row > div.row').clone();

  $('#add-dependent-btn').click(function() {
    var totalRow = $('div.dependent-row > div.row').length;
    addRow(totalRow + 1);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-dependent-btn">
  Add row
</button>
<div class="dependent-row">
  <div class="row" style="border:1px solid #ccc; padding: 5px; margin: 10px 0;">
    <label>First Name</label>
    <input type="text" value="" class="firstName dependentfield">
  </div>
</div>

这篇关于添加具有动态字段名称的新字段将字段名称设置为相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆