jQuery .val() setter not working?

If you ever use jQuery's .val() function to set the value of an input (in my case, a hidden one), there's something you might not be aware of.

In my implementation, I had this in the code:

  1. <input type="hidden" name="viewonly" id="trial-viewonly" value="" />

And was trying to override it with

  1. $('#trial-viewonly').val('No');

But it seemed as if jQuery's .val() was not working in Firefox or IE, but it worked fine in Chrome! Using .attr() didn't work either... Yet strangely, I could run an alert which would return the right value, yet Firebug still displayed a blank value:

  1. $('#trial-viewonly').attr('value', 'No');
  2. alert($('#trial-viewonly').val()); //alerts No

Why? After what seemed like an age trying to work out the problem, it came down to the value="". In the past, I've had to set certain attributes specifically to be able to use them with certain jQuery things, but it seems in this case that would break it in certain browsers. Once I removed the value attribute from my hidden input tag, it worked a treat... Something to keep in mind for next time me thinks.

  • anon

    Nice blog! Thank you for maintaining it. Keep working that way.

  • http://rubyonrails4ror.com Awijeet

    Because, the val() function works for val written inside. as an example.
    India then with val you are going to get India, where as in your example, you want to alter the value attribute. So only that is working

    • codeM0nK3Y

      It looks like wordpress has stripped the code from your comment, effectively removing your example. Would you mind reposting the example? You could try replacing the less-than/greater-than signs with square brackets to stop it deleting stuff.