19 days ago

Reworded: Add the value to the input array field using push.

How can I add elements to an input array?

To add elements to an input array, you can use the following code:

<input type="hidden" class="deleted-images" name="deletedImages[]" value="">
Then you can use JavaScript to add elements to this array. Here's an example:

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';
       removedImagesInput.value = deletedImages.join(',');

With this code, you can get the desired array in PHP:

deletedImages => [1,2,...n]
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:
  $deleted_images = $_POST['deletedImages'];
  foreach ($deleted_images as $image_id) {
     // Do something with each $image_id