2016-03-07 51 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... */); 
相關問題