Monthly Archives: May 2016

Adjust or change hidden value in form before submit with JQuery does not work

So here’s something rather odd, if you have a form:

<form id="process" action="/form-submit-url" method="post">
  <input id="myinput" name="mydata" type="hidden" />
  <button type="submit">Submit</button>
</form>

And you try and populate the hidden mydata input using jquery before the form submits:

 $(document).ready(function() {
   $('#process').submit(function(event) {
     $('#myinput').val('hello world')
   });
 });

It won’t work. You can’t do any of these sort of things either:

 $('input[name=mydata]').val('hello world');
 $('#myinput').attr('value', 'hello world');
 etc 

You have to do:

$('input[name=mydata]').val('hello world'); 

Quite strange. See http://stackoverflow.com/questions/2979772/set-value-of-hidden-field-in-a-form-using-jquerys-val-doesnt-work

The non-jquery method works fine!

document.getElementById("mydata").value = 'hello world';