Search code examples
javascriptformshiddenecmascript-5

Can not set hidden field of form


I am trying to set an input of type hidden in a form before submitting it and i do not understand why it does not set my field:

HTML

    <form id="createForm" method="post" action="[myhost]/[myaddress]/[mypath]" enctype="multipart/form-data" >
      <input type="hidden" id="ticket" name="Ticket" />
    </form>

   <input id="setterInput" type="text"/>
   <button onclick="methods.setHidden()"></button>

JS

window.methods = {
    setHidden: function () {
            var form = document.getElementById('createForm');
            var setter=document.getElementById('setter');
            var input = document.getElementsByName('Ticket');
            input.value = setter.value;
            console.log(input.value); //has the desired value
      //looking with the debugger in my form at the target input, the value is still default
    }

}

When i set the debugger in the console.log line the input variable is set.But it does not get reflected in the form. When i scroll through the form the value of the input is still "".

Any suggestions ?


Solution

  • getElementsByName returns an array of elements, even if there is just one element.

    You could do two things:

    Change this:

    var input = document.getElementsByName('Ticket');
    

    to this:

    var input = document.getElementById('ticket');
    

    Or if you wanted to keep using getElementsByName, you could access its value like this:

    var input = document.getElementsByName('Ticket')[0];