javascript 将值推送到输入数组字段

watbbzwu  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(73)

我如何添加元素到输入名称为数组?

<input type="hidden" class="deleted-images" name="deletedImages[]" value="">
const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');

deleteButtons.forEach((item) => {
    item.addEventListener('click', function () {
       item.closest('.input-photo-preview').style.display = 'none';
       removedImagesInput.value += parseInt(item.getAttribute('data-image-id')) + ',';

    });
})

在PHP的输出中,我想得到一个数组:

deletedImages => [1,2,...n]
sauutmhj

sauutmhj1#

为了让PHP接收一个数组,你需要多个name="deletedImages[]"元素。例如,您可以为每个新值克隆现有的.deletedImages元素:

const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');
const removedImagesInputParent = removedImagesInput.parentNode;
//prevent submitting empty value
removedImagesInputParent.removeChild(removedImagesInput);

deleteButtons.forEach((item) => {
    item.addEventListener('click', function () {
       item.closest('.input-photo-preview').style.display = 'none';
       //create new <input> element
       const elInput = removedImagesInput.cloneNode(false);
       elInput.value = item.getAttribute('data-image-id');
       //insert new <input> into DOM
       removedImagesInputParent.appendChild(elInput);
    });
})

否则,你需要发送JSON或逗号分隔的文本(正如你所做的那样),并在php中将其解码为一个数组,如下所示:

$deletedImages = explode(",", $_POST['deletedImages']);

相关问题