-4

How do I use javascript to append the value of an input when it has the attribute "multiple"?

i.e. <input type='hidden' name='test[]' multiple>

So like how you would set the value of a normal input document.getElementById("myId").value = "whatever"; but to work with an input that has the attribute 'multiple'

8
  • I have no clue what you are asking. Your question needs more details. I assume it should be type="file" Commented Mar 31, 2020 at 20:22
  • Sorry, what? multiple is only valid for <select> or <input type="file">. And using Vanilla JS you can set/unset attributes assigning the value of the property directly element.multiple=true|false. Commented Mar 31, 2020 at 20:25
  • 1
    @Gabriel multiple is valid for input type="file" Commented Mar 31, 2020 at 20:26
  • Multiple on an input only applies to file or email fields MSDN. But like @Gabriel said you probably need <select> Commented Mar 31, 2020 at 20:27
  • Yes, sorry, my bad, I added it before you pointed it. Commented Mar 31, 2020 at 20:27

2 Answers 2

0

I am trying to set the value of the input, not the attribute. By set, I mean append because it is a 'multiple' input

The multiple attribute does not apply to hidden inputs.

If you want to append to the value, then read the current value, and include it in the new value.

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

Since you've used PHP-style naming conventions, possibly you want to create an additional input:

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

So the submitted data will be treated as an array of values in whatever is processing it once submitted.

Sign up to request clarification or add additional context in comments.

1 Comment

This was super helpful. Thanks :)
-1

Try this:


<select id="select">
    <option>...</option>
</select>

<script defer>
    document.querySelector("#select").setAttribute("multiple", "multiple")
</script>

1 Comment

I am trying to set the value of the input, and by set I mean append because it has the attribute 'multiple'. Sorry if the question was vague. I edited it to hopefully reflect this better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.