I Have used jquery 1.8.3 to Dynamically Create the Element. But It doesn't working on this. but It's working on 1.3.2 version. Below is My Jquery Code Which I Have used for that.
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'CallBackDiv' + counter);
newTextBoxDiv.after().html('<label>Call Back Date Time #'+ counter + ': </label>'+
'<div class="controls"><input type="text" name="callback' + counter +
'" id="callback' + counter + '" value="" ></div>');
newTextBoxDiv.appendTo("#control-group");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#CallBackDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "
CallBack #" + i + " : " + $('#callback' + i).val();
}
alert(msg);
});
});
<div id='control-group'>
<div id="CallBackDiv1">
<label class="control-label" for="input01">
Call Back Date Time #1:</label><div class="controls">
<input type='textbox' id='callback1' ></div>
</div>
</div>
<input type='button' value='+' id='addButton'>
<input type='button' value='-' id='removeButton'>
Using jQuery you can dynamically create elements like this:
// Create a new div
var newTextBoxDiv = $('<div/>', {
id: 'CallBackDiv' + counter
});
// Append the new element to the DOM
newTextBoxDiv.appendTo("#control-group");
// You can check the console for the 'newTextBoxDiv' id
console.log(newTextBoxDiv.attr('id'));
// Then call the after part
newTextBoxDiv.after().html('...');
There's nothing wrong with the way you are creating the div
. The problem with your code is your use of jQuery's after()
function. Calling after()
on a newly created element will return null
, which you are then calling the html()
method on. I suggest you read up on how to use the after()
function -> http://api.jquery.com/after/
why dont you do it in plain js
var newTextBoxDiv = document.createElement('div');
newTextBoxDiv.setAttribute("id", 'CallBackDiv' + counter);