I have the following html which displays 3 textboxes and an add button:
&l
$(document).ready(function() {
$('#imgBtnAddNewLineItem').click(function() {
$('#container').append('<div></div>');
});
});
Update 2
Create a normal button like so:
<input type="button" id="imgBtnAddNewLineItem" value="Add lineitem" />
Update ** This is also updated with comments etc.. **
//Count the lineItems to make sure they are unique
var lineItemCount = 0;
//On document ready
$(document).ready(function() {
//On button click
$('#imgBtnAddNewLineItem').click(function(e) {
/*
ADD THE FOLLOWING LINE TO PREVENT THE POSTBACK
P.S. - Make sure you pass -e- to this function...
*/
e.preventDefault();
//Increase the lineitemcount
lineItemCount++;
//Add a new lineitem to the container, pass the lineItemCount to make sure getLineItem() can generate a unique lineItem with unique Textbox ids
$(container).append(getLineItem(lineItemCount));
});
});
//Create a new DIV with Textboxes
function getLineItem(number) {
var div = document.createElement('div');
//Give the div a unique id
div.setAttribute('id','lineitem_' + number);
//pass unique values to the getTextbox() function
var t1 = getTextbox('txt_' + number + '_1');
var t2 = getTextbox('txt_' + number + '_2');
var t3 = getTextbox('txt_' + number + '_3');
div.appendChild(t1);
div.appendChild(t2);
div.appendChild(t3);
return div;
}
//Create a textbox, make sure the id passed to this function is unique...
function getTextbox(id) {
var textbox = document.createElement('input');
textbox.setAttribute('id',id);
textbox.setAttribute('name',id);
return textbox;
}
Try something like this:
$(document).ready(function() {
$('#imgBtnAddNewLineItem').click(function() {
var container = $("#container");
var line = $('#line-item').clone().attr("id", "line-item-2")
var lineCount = container.children().length + 1;
line.attr("id", line.attr("id") + "-" + lineCount);
line.find(":text").each(function() {
// IDs need to be unique
$(this).attr("id", $(this).attr("id") + "-" + lineCount);
$(this).attr("name", $(this).attr("name") + "-" + lineCount);
// clear the value since we're cloning a line that may have values in it
$(this).val("");
});
container.append(line);
});
});
Note: you need to change the id.
You can use .append() method or .html()