Jquery – Set value of hidden field in a form using jQuery’s “.val()” doesn’t work

hidden-fieldsjqueryset

I've been trying to set the value of a hidden field in a form using jQuery, but without success.

Here is a sample code that explains the problem. If I keep the input type to "text", it works without any trouble. But, changing the input type to "hidden", doesn't work !

<html>

    <head>
        <script type="text/javascript" src="jquery.js">
        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                $("button").click(function() {
                    $("input:text#texens").val("tinkumaster");
                });
            });
        </script>
    </head>

    <body>
        <p>
            Name:
            <input type="hidden" id="texens" name="user" value="texens" />
        </p>
        <button>
            Change value for the text field
        </button>
    </body>

</html>

I also tried the following workaround, by setting the input type to "text" and then using a "display:none" style for the input box. But, this also fails !
It seems jQuery has some trouble setting hidden or invisible input fields.

Any ideas? Is there a workaround for this that actually works?

Best Answer

:text will fail for a input with a type value of hidden. It's also much more efficient to just use:

$("#texens").val("tinkumaster");

ID attributes should be unique on a web page, make sure yours are as this may contribute to any problems you're having, and specifying a more complicated selector just slows things down and doesn't look as neat.

Example at http://jsbin.com/elovo/edit, using your example code at http://jsbin.com/elovo/2/edit