I'm new to jQuery and am trying to just create a load of simple test rows and be able to create new rows by clicking the add button and remove each row by clicking their corresponding 'delete' text. For some reason, whenever the first row is deleted, I can no longer add new rows.
Here's the HTML:
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='all'>
<button class='add'>Add</button>
<div class='row'>hi - <span class='del'>delete</span></div>
</div>
And the jQuery:
var row, add, rows;
$(document).ready(function(){
row = $('.row'); // problem? because it's not a clone?
add = $('.add');
rows = $('.row');
add.on("click", function(){
row.clone().appendTo($('#all')); // problem? because it's now gone?
rows = $('.row');
updateRows();
});
});
function updateRows() {
rows.on("click", ".del", function(){
$(this).parent().fadeOut(1000, function(){
$(this).remove();
});
rows = $('.row');
});
}
I've also made a CodePen demo if that helps. So my question is, why does the 'add' button stop working after the first row is deleted? I wonder whether once the first row is deleted, it can't be appended as the variable is then deleted, and if I'm right, how can you create a variable clone that stays even when it's deleted (if you know what I mean)?
Thanks for any help here - any explanations would be much appreciated.