37789037

http://stackoverflow.com/questions/37789037/how-to-rename-all-id-in-a-cloned-form-javascript/37796797?noredirect=1#comment63078161_37796797

by Gjermund Dahl

HTML

<form>
  <div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="horizontal">
      <legend>Address:</legend>
      <label><input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />Address 1</label>
      <label><input type="radio" name="radio-address" id="radio-address_male" value="2" />Address 2</label>
    </fieldset>
  </div>
  <div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
    <label for="foo" id="age">Age:</label>
    <input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">
  </div>
</form>

<hr>

<form>
  <div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="horizontal">
      <legend>Address:</legend>
      <label><input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />Address 1</label>
      <label><input type="radio" name="radio-address" id="radio-address_male" value="2" />Address 2</label>
    </fieldset>
  </div>
  <div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
    <label for="foo" id="age">Age:</label>
    <input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">
  </div>
</form>

<hr>

JavaScript

var i = 0,
  currentPrefix = "form";
$("form").each(function() {
  $(this).find("input, select").each(function() {
    $(this).attr("id", currentPrefix + i + "_" + $(this).attr("id"));
    $(this).attr("name", currentPrefix + i + "_" + $(this).attr("name"));
  });
  i++;
});