I am trying to add dynamic textboxes using Javascript.
When someone clicks on the Add More Link than 2 text boxes will be added dynamically.
I have the HTML code which I want to repeat when someone clicks on Add More link.
<div class="row">
<div class="left">Employer</div>
<div class="right"><input type="text" class="tripObject" name="employer" id="employer" value=""> <strong>Position</strong> <input type="text" class="tripObject" name="position" id="position" value=""> <a href="javascript:addFormField();">Add More</a>
</div>
</div>
And the JavaScript code is:
window.optionId =1;
window.addFormField = function() {
optionId += 1;
var thisOption = $('<div>', {
'class': 'row ' + optionId
}).append(
$('<div>').attr({
'class': 'left'
}).html('Employer'),
/*$('<div>').attr({
'class': 'right'}),*/
$('<input>').attr({
'type': 'text',
'size': 20,
'name': 'option_' + optionId,
'class': 'tripObject',
'validate': 'required:true'
}),
$('<a>').attr({
'href': '#'
}).html('Remove').click(function() {
thisOption.remove();
})
).appendTo('#editeducationInfo');
};
Why are you making it complex? As you are using
jqueryin your code, here is the easy way of appending the existing elements bycloneandappendmethod.Doc: $.append(), $.clone()
Update:
Check this fiddle