Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - How can I clone a form and change the id of its children more than just once?

I have been trying to clone a section which is part of a form, which I have successfully completed. But I need to work with the data and so I need to change the ID's of the element's children (input, select ecc). I have been looking a while in the web but nothing really works for me, also because I would like to clone the element more often, also the ID should change then everytime. Can you help me with that? Would be great:

HTML:

<div class="input-form fcf-form-group">

  <div class="form only">
    <h3 class="fcf-h3">Room</h3>
    <div class="form-section">

      <div class="title-group">
        <label for="room" class="fcf-label">Room</label>
        <select name="room" id="room" required>
          <option value="double">Double</option>
          <option value="single">Single</option>
        </select>
      </div>
    </div>
  </div>

  <div class="form neighbour">

    <div class="title-group small">
      <label for="adults" class="fcf-label">Adults</label>
      <input type="number" id="adults" name="adults" min="1" max="5">
    </div>

    <div class="title-group small">
      <label for="child" class="fcf-label">Children</label>
      <input type="number" id="child" name="child" min="1" max="5">
    </div>

    <div class="title-group small">
      <label for="age" class="fcf-label">Age of the Child</label>
      <select name="age" id="age" required>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </div>
  </div>
</div>
</div>

JQUERY:

$('#but_add').click(function () {

  // Create clone of <div class='input-form'>
  var newel = $('.input-form:last').clone();

  // Add after last <div class='input-form'>
  $(newel).insertAfter('.input-form:last');
});
})
question from:https://stackoverflow.com/questions/65893536/how-can-i-clone-a-form-and-change-the-id-of-its-children-more-than-just-once

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can first clone the form via a selector (as you do) and search for every form element (input and select) via multiple selector. Once you have them stored, you can map them and then update the input element id via .attr to add index for every time you do this (ex: room, then room1, then room, ...). To be clear you could rename every id in your initial HTML with '0' (ex: room0).

At the end you will have your form data with every id incremented.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...