Technologies:
Tolerim
19 days ago
Reworded: Add the value to the input array field using push.
<input type="hidden" class="deleted-images" name="deletedImages[]" value="">
const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');
let deletedImages = [];
deleteButtons.forEach((item) => {
item.addEventListener('click', function () {
item.closest('.input-photo-preview').style.display = 'none';
deletedImages.push(parseInt(item.getAttribute('data-image-id')));
removedImagesInput.value = deletedImages.join(',');
});
})
deletedImages => [1,2,...n]
Answers(1)
Tolerim
19 days ago
Verified Answer
To add elements to input with name as an array, you can simply use square brackets [] after the name attribute value. In your provided example, the input element already has an attribute name="deletedImages[]", which means that its value will be sent as an array when the form is submitted.
In the JavaScript code you provided, the value of removedImagesInput input element is being updated using the += operator inside the click event handler of the delete buttons. This line of code is concatenating the IDs of the images, separated by a comma, to the existing value of removedImagesInput.
Assuming the form submission method is POST, you can receive the deletedImages values as an array in PHP using the $_POST superglobal variable. Here's an example of how you can loop through the array in PHP:
if(isset($_POST['deletedImages'])){
$deleted_images = $_POST['deletedImages'];
foreach ($deleted_images as $image_id) {
// Do something with each $image_id
}
}