首页 > 解决方案 > Javascript 使用“多个”属性附加输入

问题描述

当输入具有“多个”属性时,如何使用 javascript 附加输入的值?

IE<input type='hidden' name='test[]' multiple>

就像您如何设置普通输入的值一样,document.getElementById("myId").value = "whatever";但要使用具有“多个”属性的输入

标签: javascripthtmlforms

解决方案


我正在尝试设置输入的值,而不是属性。通过设置,我的意思是追加,因为它是一个“多个”输入

multiple属性不适用于hidden输入。

如果要附加到值,则读取当前值,并将其包含在新值中。

input.value = input.value + "some other string";

由于您使用了 PHP 风格的命名约定,因此您可能想要创建一个额外的输入:

const newInput = document.createElement("input");
newInput.name = "test[]";
newInput.type = "hidden";
newInput.value = "some other string";
input.insertAdjacentElement("afterend", newInput);

因此,提交的数据将被视为一个值数组,在提交后处理它的任何内容。


推荐阅读