2016-03-07 88 views
0

js文件如何在创建动态输入字段时为相同的输入类型获取单独的ID?

在下面的JavaScript文件中我怎样才能创建不同的输入类型id每当新的输入类型正在创建。

$(document).ready(function(){ 
     $(".template_charge:first").hide(); //hide template 
     var charge_count =0; // Total charge types. 
     var charge_id_no =0; // To assign id and name to charge component 
     /* Add new item based on hidden template */ 
     $(".add_charge").click(function() { 
      charge_id_no ++; 
      charge_count ++; 
      $('#charge_count').val(charge_count); 
      var newItem = $(".template_charge:first").clone(); 
      newItem.find("input").attr("id", "chargeType_" + charge_id_no); //rewrite id's to avoid duplicates 
      newItem.find("input").attr("name", "chargeType_" +charge_id_no); 
      newItem.find("input").attr("id", "charge_" +charge_id_no); //rewrite id's to avoid duplicates 
      newItem.find("input").attr("name", "charge_" +charge_id_no); 
      newItem.show(); //show clone of template 
      $(".template_charge:last").after(newItem); 

      bindRemove(); 
     }); 

     /* Bind remove function to last added button*/ 
     function bindRemove() { 
      $(".remove_charge:last").click(function(e) { 
      if ($(".remove_charge").length > 1) 
       $(this).parents(".template_charge").remove(); 
       charge_count--; 
       $('#charge_count').val(charge_count); 
      }); 
     } 

     /* Execute bind-function at startup */ 
     bindRemove(); 
}); 

HTML文件

Html文档如果每次单击添加按钮为其创建输入类型。

<input type="hidden" id="charge_count" name="charge_count" value="0"/> 
        <div class="form-group col-md-12" id="other_charge"> 
        <div class="form-group col-md-12 col-sm-12"> 
        <label for="Other_charges" class="control-label col-md-2">Other Charges</label> 
        <button id="b2" class="btn btn-info add_charge col-md-10 col-sm-12" type="button">Add</button> 
         <div class="template_charge col-md-offset-2"> 
         <div class="controls" id="profs"> 
          <div id="field_charge" class="form-group input-append col-md-12"> 
          <input autocomplete="off" class="input form-control col-md-5" id="field3" name="charge1" type="text" placeholder="Charge type" /> 
          <input autocomplete="off" class="input2 form-control col-md-5" id="field4" name="charge2" type="text" placeholder="Charge" min="0" max="100" /> 
          <button class="remove_charge btn btn-danger form-control col-md-2" type="button">X</button> 
          </div> 
         </div> 
         </div> 
        </div> 
        </div> 
+0

当'input'元素被删除应该''剩余元素input'来调节或保持的id'一样吗? – guest271314

+0

'#profs'元素如果未在克隆元素上进行调整,也会在文档中重复'id' – guest271314

回答

0

...有点猜测,而不能看到的模板,但也许模板根已经是input,因此调用find返回零长度设定,所以不能正常工作。尝试这种...

newItem.find("input").attr(/* etc... */); 

......应读...

newItem.attr(/* etc... */); 
相关问题