Home > Mobile >  Cloning a div tag while also changing id attributes of it elements using JavaScript (Multiple elemen
Cloning a div tag while also changing id attributes of it elements using JavaScript (Multiple elemen

Time:01-30

I am looking to clone a div while also changing id's of the elements inside the mentioned div

The code i am using clone the div is

<!DOCTYPE html>
<html lang="en">
<body>
  <form>
      <div  id="dynamic-field-1">
          <div>
      <label for="name" >Name</label>
      <input type="text" id="name-1"  name="field[]" />
    </div>
    <div>
      <label for="age" >Age</label>
      <input type="text" id="age-1"  name="field[]" />
    </div>
      </div>
      <div>
        <button type="button" id="add-button">
          Add
        </button>
      </div>
  </form>
  <script src='https://code.jquery.com/jquery-3.3.1.slim.min.js'></script>
  <script>
    $(document).ready(function () {
      var buttonAdd = $("#add-button");
      var className = ".dynamic-field";
      var count = 0;

      function totalFields() {
        return $(className).length;
      }

      function addNewField() {
        count = totalFields()   1;
        field = $("#dynamic-field-1").clone();
        field.attr("id", "dynamic-field-"   count);
        field.find("input").val("");
        $(className   ":last").after($(field));
      }


      buttonAdd.click(function () {
        addNewField();
      });

    });
  </script>
</body>

</html>

The code used can clone div and change its id in an incremental manner. the problem is changing the element input id and name of the label

the cloned div's element's id needs to be like eg field-1,field2,..etc

The expected Result is..

<form>
<div  id="dynamic-field-">
    <div>
        <label for="name" >Name</label>
        <input type="text" id="name-1"  name="field[]" />
    </div>
    <div>
        <label for="age" >Age</label>
        <input type="text" id="age-1"  name="field[]" />
    </div>
</div>
<div  id="dynamic-field-2">
    <div>
        <label for="name" >Name</label>
        <input type="text" id="name-2"  name="field[]" />
    </div>
    <div>
        <label for="age" >Age</label>
        <input type="text" id="age-2"  name="field[]" />
    </div>
</div>
<div>
    <button type="button" id="add-button">
        Add
    </button>
</div>

How can i achieve by altering the existing code and not using an entirely different method

CodePudding user response:

Using Jquery attr:

field.find("input").attr("id","field-"   count);
field.find("label").attr("for","field-"   count);
  • Related