views:

1070

answers:

6

So, I'm going crazy for this. I have a simple input field inside a form tag.

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

  </form>

I tried to set his value from a js file but in the html value attribute isn't set at all.

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

If I trie to set the input type to "button" or anything else, it work. I can't do it with hidden type input field. What did i do wrong??

+1  A: 

Would it help if you give the input field an initial value? (even if it is an empty string)

Jasper De Bruijn
I's also try this
Natrium
A: 

I'd need to see the whole file but my guess is either you aren't including the jQuery.js source file or you have multiple elements with an ID of foo

Andrew G. Johnson
+3  A: 

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());
})
Fermin
A: 

I figured it out. The value was set by jqeruy, but when i open the source the attr value didn't appear. I treid this(thanks to Fermin)

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

and it alerted the right value. Thanks guys

framomo86
I recommend using a dev tool like firebug for firefox to see dynamic source code more easily.
David
If Fermin answered your question you should mark it as the accepted answer.
thenduks
A: 

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)

Stevie G
A: 

I had the same problem with a hidden input field. Id i set the initial value on 0, it works fine, but sometimes i didn't want to have an initial value of 0. So i tested with value=" ", a whitespace, and it works for me too. If you fill the value dynamic from PHP you could do value="<?= $val+0; ?>" if 0 is fine for you, or value="<?= $val; ?> " if a whitespace is fine.

mtom