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';

2 thoughts on “Adjust or change hidden value in form before submit with JQuery does not work

  1. Valane Adam Lusk

    I don’t know when this was written, but the non jquery way that you say works for you does not work for me. I’m working with Rails 5 and when I submit the form and pry into the controller, I have a key pointing to an empty value. I suspect the value is still back there on the form but it wasn’t sent with the form submission.

    Reply
  2. Toby Crain

    Yeah, it’s weird that the val() method does not populate. But using the attr() method does in all my tests.

    jQuery(fieldId).attr(‘value’, newFieldValue);

    Reply

Leave a Reply to Toby Crain Cancel reply

Your email address will not be published. Required fields are marked *