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?
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.
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.
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());
})
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.
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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With