I have a dynamic formset where the user can click a button to remove forms from the formset before clicking submit. I've achieved this by applying some javascript to the button tag. This is a django app.
My issue arises when I add a trash can icon as the button's image. The image itself is not clickable and dynamic (i.e. removing the form when clicked), but the button area around the image is. I would like the entire thing to be clickable.
When trying to click the trash icon itself, nothing happens, and the console logs this error:
Uncaught TypeError: Cannot set properties of null (setting 'checked') at HTMLButtonElement.removeIngredient
When tracing this error, I encounter the following in the chrome console sources tab:
This image corresponds with the javascript below
HTML
<button class="remove-button" id="remove-ingredient" type="submit"><img src="{% static 'inventory/trash-icon.png' %}"></button>
CSS
.remove-button {
border: none;
width: 100%;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
}
.remove-button img {
height: 20px;
width: 20px;
}
.remove-button:hover {
cursor: pointer;
}
Javascript
function removeBtnListener () {
const removeIngredientBtns = document.getElementsByClassName('remove-button')
for (let i = 0; i < removeIngredientBtns.length; i++) {
removeIngredientBtns[i].addEventListener('click', removeIngredient)
}
}
function removeIngredient (event) {
if (event) {
event.preventDefault()
}
let ingredientFormToBeRemoved = event.path[1]
let indexString = ingredientFormToBeRemoved.id
let array = indexString.split('-')
let indexNum = array[2]
let deleteCheckbox = document.getElementById(`id_ingredientquantity_set-${indexNum}-DELETE`)
deleteCheckbox.checked = true
ingredientFormToBeRemoved.setAttribute('class', 'hidden')
}
Does anyone know how to make this work so the entire element removes the form properly when clicked?