The user can delete new field input rows by by clicking on the ‘-‘ button for that particular row. The user also has the ability to add new field input rows. The JS code that I've written works for the existing rows, but it doesn't work for any of the new dynamically created lines that are added by clicking the '+' button.
I've tried changing
$(".remove-current-ing").click(function() {...}
to
$(".remove-current-ing").on('click', function() {...}
HTML code:
<div class="row card z-depth-1">
<h3><i class="fas fa-pizza-slice"></i> Ingredients</h3>
{% for ing in recipe.ingredients %}
<div class="input-field ingredients col s12">
<input id="ingredients" name="ingredients" type="text" placeholder="Ingredient (one per line)" class="form-control validate" value="{{ ing|capitalize }}" required>
<label for="ingredients"></label>
<!--BUTTON THAT ISN'T WORKING ON DYNAMICALLY CREATED ROWS-->
<a class="waves-effect waves-light btn remove-current-ing">
<i class="fas fa-minus material-icons" aria-hidden="true"></i>
</a>
</div>
{% endfor %}
<!--Add Ingredient Row Btn-->
<button type="button" class="waves-effect waves-light btn add-ing">
<i class="fas fa-plus material-icons" aria-hidden="true"></i>
</button>
<!--Remove Ingredient Row Btn-->
<button type="button" class="waves-effect waves-light btn remove-ing">
<i class="fas fa-minus material-icons" aria-hidden="true"></i>
</button>
</div>
JS code:
let ingCount = $(".ingredients").length;
// Add new line
$(".add-ing").click(function() {
// Clone line, insert before add/remove btns and clear existing values
$(".ingredients:first").clone().insertBefore(".add-ing").find("input[type='text']").val("");
// Ensures original line is never removed
ingCount += 1;
});
// Remove last line
$(".remove-ing").click(function() {
// Ensure that the first line can't be removed
if (ingCount > 1) {
$(".ingredients:last").remove();
ingCount -= 1;
}
});
/* Remove the current ingredient (edit_recipe.html) */
/* CODE THAT ISN'T WORKING ON DYNAMICALLY CREATED ROW */
$(".remove-current-ing").on('click', function() {
// Ensure that the first line can't be removed
if (ingCount > 1) {
$(this).parent().remove();
ingCount -= 1;
}
});```
The .remove-current-ing
button works on pre-exisiting rows and removes them, but it doesn't work on new dynamically created rows (nothing happens when pressed).