Reputation: 433
I have used the following way to add multiple div on clicking "addButton", as given in below fiddle :
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();
});
});
I have to add the text using html and append it thereafter. Is there any other way to solve this issue in Bootstrap?
Upvotes: 2
Views: 27657
Reputation: 8726
Try this
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();
});
});
Upvotes: 6