jqueryhidden-field

Can't set hidden input field's value using jQuery


I have a simple input field inside a form tag:

<body>
  <form action="#">
      <label>Input</label>
      <input type="hidden" id="foo" name="foo" />

  </form>
</body>

I tried to set this value from a js file:

$(document).ready(function(){
    $('#foo').val('foo')
})

but in the html source the attribute isn't set at all. If I try to set the input type to "button" or anything else, it works. I just can't do it with a hidden input field. What am I doing wrong?


Solution

  • Can you retrieve the value from the hidden field if you set the val tag?

    e.g.

    <input type="hidden" id="foo" name="foo" value="bar" />
    
    $(document).ready(function(){
      alert($('#foo').val());
    })