2013-06-22 100 views
2

我用以下方式對點擊「Add按鈕」添加多格,如下面給出的小提琴:如何在bootstrap中添加動態div?

http://jsfiddle.net/harshmadhani/jpb93/

$(document).ready(function() { 
var counter = 2; 
$("#addButton").click(function() { 
     if (counter > 2) { 
      alert("Only 2 textboxes allowed"); 
      return false; 
     } 
     $('<div/>',{'id':'TextBoxDiv' + counter}).html(
      $('<label/>').html('Textbox #' + counter + ' : ') 
     ) 
     .append($('<input type="text">').attr({'id':'textbox' + counter,'name':'textbox' + counter})) 
     .appendTo('#TextBoxesGroup')  
     counter++; 
    }); 

    $("#removeButton").click(function() { 
     if (counter == 1) { 
      alert("No more textbox to remove"); 
      return false; 
     } 
     counter--; 
     $("#TextBoxDiv" + counter).remove(); 
    }); 
}); 

我必須用HTML添加文本,然後追加它。有沒有其他方法可以解決Bootstrap中的這個問題?

+0

你說的意思'我有使用HTML來添加文本和追加它thereafter' ? – Starx

+0

@Starx:這意味着我必須使用像html這樣的jQuery方法,並在點擊按鈕 –

+0

後追加,你需要更深入的描述。 bootstrap是一個css基礎,並提供了像旋轉木馬,風格下拉等東西的小部件。你不能這樣做'append'工作_using_ bootstrap,ul必須使用jQuery。 – krishgopinath

回答

6

試試這個

http://jsfiddle.net/jpb93/3/

HTML

<div class="form-horizontal"> 
     <div class="control-group"> 
      <label class="control-label" for="inputEmail"> 
       Email</label> 
      <div class="controls"> 
       <input type="text" id="inputEmail" placeholder="Email" /> 
       </div> 
     </div> 
    </div> 

的jQuery:

$(document).ready(function() { 

      $("#addButton").click(function() { 
       if(($('.form-horizontal .control-group').length+1) > 2) { 
        alert("Only 2 control-group allowed"); 
        return false; 
       } 
       var id = ($('.form-horizontal .control-group').length + 1).toString(); 
       $('.form-horizontal').append('<div class="control-group" id="control-group' + id + '"><label class="control-label" for="inputEmail' + id + '">Email' + id + '</label><div class="controls' + id + '"><input type="text" id="inputEmail' + id + '" placeholder="Email"></div></div>'); 
      }); 

      $("#removeButton").click(function() { 
       if ($('.form-horizontal .control-group').length == 1) { 
        alert("No more textbox to remove"); 
        return false; 
       } 

       $(".form-horizontal .control-group:last").remove(); 
      }); 
     }); 
+0

更新我的答案檢查 –

+0

我可以在jQuery中使用clone()來複制完整的div嗎?因爲我需要添加很多div元素。 –

+0

Works Awesome !!! – VSN