附加具有唯一ID的新字段

时间:2019-07-16 08:34:45

标签: javascript jquery html

我有带名字和数字的代码。我想要一个按钮,当您单击它时,会为另一个名称和数字添加另一个字段,但是它应该具有不同的ID,因为以后需要使用它。

到目前为止,我有下面的代码,但是它不起作用。

function addField() {
  var id = 2
  var name = 'Name of Owner # ' + id
  var phonenum = 'Phone number'

  $('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')

  $('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')

  id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
  <fieldset>
    <legend>
      <code>New Phone Number</code>
    </legend>

    <label for="NewPnOwner">Name of Owner #1:&nbsp;</label>
    <input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner" />
    <br />
    <label for="Phonenumber">Phone number: &nbsp;&nbsp; </label>
    <input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
    <br />    
    <input type="button" id="button" value="Add New Field" onclick="addField()" />
  </fieldset>
</div>

1 个答案:

答案 0 :(得分:0)

只需在函数外部定义id,否则它将在每次2的调用时以值addField()初始化。

var id = 2
function addField() {
  var name = 'Name of Owner # ' + id
  var phonenum = 'Phone number'

  $('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')

  $('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')

  id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
  <fieldset>
    <legend><code>New Phone Number</code></legend>

    <label for="NewPnOwner">Name of Owner #1:&nbsp;</label>
    <input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner">
    <br>
    <label for="Phonenumber">Phone number: &nbsp;&nbsp; </label>
    <input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br>    
<input type="button" id="button" value="Add New Field" onclick="addField()" />
  </fieldset>

</div>

但是

即使这是解决问题的正确方法,我也不建议您给他们这样的ID。我想不出任何有效的理由来解决类似的问题。对于您的实际问题,可能有更好的解决方案。