Reputation: 180
I set event listener to button and expect new node adding every time the button is pressed, but, in fact, this works only one time. That must be my mistake with ":last" selector which somehow freezes on the same node. How can I fix this?
$("#btnAddWord").on('click', function(){
$('div.input-group:last').after( inputGroup );
});
Upvotes: 0
Views: 224
Reputation: 1053
$("#btnAddWord").on('click', function(){
var inputGroup = document.createElement('div');
inputGroup.setAttribute('class','input-group');
inputGroup.innerHTML = '<span class="input-group-addon">'+
' <input type="checkbox">'+
'</span>'+
'<input type="text" class="form-control" Placeholder="New word">'+
'<span class="input-group-addon">'+
' <span class="glyphicon glyphicon-remove-circle"></span>'+
'</span>';
$('div.input-group').last().append( inputGroup );
});
Upvotes: 1
Reputation: 745
Looking at your fiddle link it seems that, inputGroup is no longer available on next click. so try this:
function CreateDiv()
{
var inputGroup = document.createElement('div');
inputGroup.setAttribute('class','input-group');
inputGroup.innerHTML = '<span class="input-group-addon">'+
' <input type="checkbox">'+
'</span>'+
'<input type="text" class="form-control" Placeholder="New word">'+
'<span class="input-group-addon">'+
' <span class="glyphicon glyphicon-remove-circle"></span>'+
'</span>';
return inputGroup;
}
$(document).on("click", "#btnAddWord", function(){
$('div.input-group:last').after( CreateDiv() );
});
Upvotes: 1
Reputation: 2156
You should use a function that generates new input groups, here you're always referring to the same element (created one time only).
function createInputGroup() {
return $('<div class="input-group">' +
'<span class="input-group-addon">' +
' <input type="checkbox">' +
'</span>' +
'<input type="text" class="form-control" placeholder="New word">' +
'<span class="input-group-addon">' +
' <span class="glyphicon glyphicon-remove-circle"></span>' +
'</span>' +
'</div>');
}
$("#btnAddWord").on('click', function(){
$('div.input-group:last').after( createInputGroup() );
});
Upvotes: 1
Reputation: 5343
you are just moving the same element from place to place (which is the same place by the way).
You need to clone this element by doing
$(inputGroup).clone()
Upvotes: 0
Reputation: 67080
It's because you try to add again and again the same element (instead of a new one). Let's create a new one for each click.
Modified code from your JSFiddle example:
$("#btnAddWord").on('click', function(){
var inputGroup = document.createElement('div');
inputGroup.setAttribute('class','input-group');
inputGroup.innerHTML = '...here your HTML...';
$('div.input-group:last').after( inputGroup );
});
Upvotes: 2