I have a function to add and remove a field but the remove function doesnt work somehow.
HTML:
<div id="parts">
Part
<input type="text" id="auto_part" name="auto_part" />
<br />
Description
<input type="text" id="auto_description" name="auto_description" />
<br />
</div>
<a href="#" id="addField">Add another part</a>
jQuery:
$(function() {
var scntDiv = $('#parts');
var i = $('#parts input').size();
$('#addField').on('click', function() {
$('<br /><div id="parts"><span>Part</span> <input type="text" id="auto_part'+i+'" name="auto_part'+i+'" /><br />').appendTo(scntDiv);
$('<span>Description</span> <input type="text" id="auto_description'+i+'" name="auto_description'+i+'" /> <br />').appendTo(scntDiv);
$('<input type="hidden" id="row_count" name="row_count" value="" />').appendTo(scntDiv);
$('<a href="#" id="removefield">Remove</a></div>').appendTo(scntDiv);
i++;
return false;
});
$('#removefield').on('click', function() {
if( i > 2 ) {
$(this).parents('div').remove();
i--;
}
return false;
});
});
The problem must have to do with this line:
$('#removefield').on('click', function() {
It doesnt pass that condition.
When I click on Remove it doesnt do anything at all it just scrolls to the top.
You are binding the
clickhandler to the elements that are present in the DOM. But, your#removefieldelement is being dynamically added. So, the event handler is not attached to it.You can use
.on()to use event delegation and handle also future elements. Also, you may want to use classnames instead of andidattributes.idattributes need to be unique, but you can set the classname to as many elements as you want.The reason why your
"Remove"link doesn’t work is because you are adding the dynamic<div>element by parts hence making it invalid markup. You should be adding it all together at once. For example,You can see it here.