Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 721
framomo86 Avatar asked Jan 21 '10 13:01

framomo86


People also ask

How do you assign a value to a hidden input?

In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.

What is the use of hidden form field?

Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data.


5 Answers

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());
})
like image 94
Fermin Avatar answered Oct 19 '22 10:10

Fermin


I figured it out. The value was set by jQuery but when I viewed the source the new value wasn't shown. I tried this (thanks to Fermin):

$('#foo').val('poo')
alert($('#foo').val())

and it displayed the modified value.

like image 40
framomo86 Avatar answered Oct 19 '22 08:10

framomo86


The best answer I found was in the form http://forum.jquery.com/topic/passing-value-to-hidden-form-field.

Instead of $('#Data').val(data); Where the hidden field ID is 'Data'

Use $('input[name=Data]').val(data);

Works perfectly for me

like image 22
Jacob Tomlinson Avatar answered Oct 19 '22 08:10

Jacob Tomlinson


I have also been struggling with this. If you set an initial value say '0', and then watch the DOM using something like Firebug you will notice that the DOM then updates. For some reason if the initial value is set to null or an empty string, the DOM does not update, but the value is actually still stored.

You can test this by alerting the val after you have set it (as suggested in earlier posts)

like image 4
Stevie G Avatar answered Oct 19 '22 08:10

Stevie G


I've had this problem when POST-ing my form and my PHP script couldn't get POST-ed value. I used this:

$('#elemId').attr("name", theValue);

Hope it helps.

like image 2
Remo Harsono Avatar answered Oct 19 '22 10:10

Remo Harsono