使用 jQuery 的“.val()"设置表单中隐藏字段的值不工作 [英] Set value of hidden field in a form using jQuery's ".val()" doesn't work

查看:19
本文介绍了使用 jQuery 的“.val()"设置表单中隐藏字段的值不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 jQuery 在表单中设置隐藏字段的值,但没有成功.

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>

我还尝试了以下解决方法,将输入类型设置为文本",然后对输入框使用显示:无"样式.但是,这也失败了!似乎 jQuery 在设置隐藏或不可见的输入字段时遇到了一些问题.

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?

推荐答案

:text 对于类型值为 hidden 的输入将失败.使用起来也更有效率:

: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 属性在网页上应该是唯一的,请确保您的 ID 属性是唯一的,因为这可能会导致您遇到任何问题,并且指定更复杂的选择器只会减慢速度并且看起来不那么整洁.

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.

http://jsbin.com/elovo/edit 中的示例,使用您在 http://jsbin.com/elovo/2/edit

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

这篇关于使用 jQuery 的“.val()"设置表单中隐藏字段的值不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆