2014-10-04 72 views
1

通過克隆html動態創建使用javascript的選擇列表,並且在選擇列表創建之後,嘗試使用$(MySelectList).selectPicker();初始化選擇列表似乎成功了,但在調用.selectPicker()後似乎重複了幾次的選擇。Bootstrap SelectPicker在初始化時複製選擇列表

如果沒有調用.selectPicker(),克隆行中有三個下拉列表,但您無法更改這些值(列表打開,但選擇不包含這些值)。

在呼叫.selectPicker()後,新行的下拉菜單會選取所選值,但現在總共有5個選擇列表。另外兩個是dup的列表。

這的確是所有有給它:

<div id="advSearchRows" class="clearfix"> 

    <!-- Form Row Template --> 

    <div class="row clone" id="ASR1"> 
     <div class="form-group"> 
      <select class="selectpicker include"> 
       <option>Must Include</option> 
       <option>Must NOT Include</option> 
      </select> 
     </div> 
     <div class="form-group"> 
      <select class="selectpicker match"> 
       <option id="-1">foo</option> 
       <option id="0">bar</option> 
       <option id="1">fubar!</option> 
      </select> 
     </div> 
     <div class="form-group"> 
      <input type="text" class="search-text form-control" placeholder="Keyword Text"> 
     </div> 
     <div class="form-group remove hidden"></div> 
    </div> 

</div> 

和行重複的代碼

var numRows = $("#advSearchRows .clone").length;  // how many rows currently 
    var lastRow = $("#advSearchRows .clone:last");   // the last row in the list 
    var lastId = lastRow.attr("id").replace("ASR", "");  // the id of the last item 
    if(numRows < 5) { // duplicate (clone) template row:  
     var id = parseInt(lastId) + 1;      // the numeric id of the new row 
     var newRow = lastRow.clone().attr("id", id);  // actual cloned row 
     newRow.find("select.include") 
      .attr("id", "include" + id) 
      .selectpicker(); // include ddl id 
     newRow.find("select.match") 
      .attr("id", "match" + id) 
      .selectpicker();  // match ddl id 
     newRow.insertAfter("div.clone:last").slideDown('slow'); 
     $("#" + id).find(".remove").removeClass("hidden"); 

我不知道是否有什麼問題我選擇... newRow.find("select.match").attr("id", "match" + id).selectpicker()但它看起來正確的根據文件...也許有一些我錯過了。

+0

請不要使用「bootstrap」標籤,使用「twitter-bootstrap」標籤,因爲它意味着其他東西 – 2014-10-12 12:45:36

回答

1

對不起,我找到了解決方案。基本上我需要一個未初始化的隱藏模板,克隆模板,然後初始化。十分簡單。

// 
// Handle "Add" row button event: 

function cloneRow() { 
    var numRows = $("#advSearchRows .clone").length; 
    var lastRow = $("#advSearchRows .clone:last"); 
    var template = $("#advSearchRows #ASR1"); 
    if (numRows >= 6) return false; 
    var id = parseInt(lastRow.attr("id").replace("ASR", "")) + 1; 
    var newRow = template.clone().removeClass("hidden").attr("id", id); 
    newRow.find("select.include").attr("id", "include" + id).selectpicker(); 
    newRow.find("select.match").attr("id", "match" + id).selectpicker(); 
    newRow.insertAfter("div.clone:last").slideDown('slow');     
    $("#" + id).find(".remove").removeClass("hidden"); 
    return false; 
}