Brad
Brad

Reputation: 12262

Adding new fields with dynamic field name sets field names to the same name

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

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

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

Upvotes: 0

Views: 597

Answers (1)

choz
choz

Reputation: 17858

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>

Upvotes: 2

Related Questions