skip to Main Content

So I have an input text with the name filesChosen[]. This input is empty. I would like through javascript to be able to add values to that input.

<input type="text" name="filesChosen[]" id="filesChosen[]" multiple="true" style="display: none" onchange="addFiles()" required>

I have tried the following but it seems to only work with the first value:

document.getElementsByName("filesChosen")[x].value = "1" ;

Is there a way to Push a new element to the input?

I am getting the following error when X >0

26:400 Uncaught TypeError: Cannot set properties of undefined (setting ‘value’)

Edit:
Change to document.getElementsByName("filesChosen[]"), getting same error

2

Answers


  1. You left the [] out of the name when calling document.getElementsByName().

    If there’s only one element with this name, you shouldn’t use a variable to index it, use [0].

    Use += to append to the value.

    document.getElementsByName("filesChosen[]")[0].value += "1" ;
    
    Login or Signup to reply.
  2. I think the style="display: none" CSS property you have on there might be interfering with your code. But if that’s not it then you could try this syntax:

    const input = document.querySelectorAll('[name="filesChosen[]"]')[0]
    input.value = 'Some value'
    <input type="text" name="filesChosen[]" id="filesChosen[]" multiple="true" onchange="addFiles()" required >
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search