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

下面是解释该问题的示例代码。如果我保持输入类型为“文本”,它工作起来没有任何麻烦。但是,将输入类型更改为“hidden”,却不起作用!

<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>

我还尝试了以下解决方法,通过设置输入类型为“text”,然后为输入框使用“display:none”样式。但是,这也失败了! jQuery似乎在设置隐藏或不可见的输入字段时遇到了一些麻烦。

什么好主意吗?有没有可行的解决办法?


当前回答

在迷失在这个页面上无数的答案之后,没有一个真正有效,我找到了如何在我的情况下做到这一点。

出于某种原因,在选择器中使用输入并没有做到这一点。我在表单元素上没有ID,所以我不能为选择器使用任何ID。即使我做了,我也肯定不会成功。

以下是我的解决方案:

$("[name=something]").val("something");

基本上,选择名称为“something”的任何元素。试试看吧。

其他回答

:text对于type值为hidden的输入将失败。只使用以下语句也会更有效率:

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

ID属性在网页上应该是唯一的,确保你的ID属性是唯一的,因为这可能会导致你遇到的任何问题,指定一个更复杂的选择器只会减慢速度,看起来不那么整洁。

http://jsbin.com/elovo/edit上的示例,使用http://jsbin.com/elovo/2/edit上的示例代码

简单地使用get和set下面的语法

GET

//Script 
var a = $("#selectIndex").val();

这里一个变量将保存hiddenfield(selectindex)的值

服务器端

<asp:HiddenField ID="selectIndex" runat="server" Value="0" />

SET

var a =10;
$("#selectIndex").val(a);

Actually, this is an ongoing problem. While Andy is right about the downloaded source, .val(...) and .attr('value',...) don't seem to actually modify the html. I think this is a javascript problem and not a jquery problem. If you had used firebug even you would have had the same question. While it seems that if you submit the form with the modified values it will go through, the html does not change. I ran into this issue trying to create a print preview of the modified form (doing [form].html()) it copies everything okay, including all changes except values changes. Thus, my modal print preview is somewhat useless... my workaround may have to be to 'build' a hidden form containing the values they have added, or generate the preview independently and make each modification the user makes also modify the preview. Both are inoptimal, but unless someone figures out why the value-setting behavior does not change the html (in the DOM i'm assuming) it will have to do.

我也有同样的问题,我找到了问题所在。我把HTML定义为

<form action="url" method="post">
    <input type="hidden" id="email" />
<form>
<script>
    function onsomeevent()
    {
       $("#email").val("a@a.com");
    }
</script>

在服务器上读取表单值总是导致电子邮件为空。在绞尽脑汁(和无数次搜索)之后,我意识到错误在于没有正确定义表单/输入。在修改输入时(如下所示),它就像一个咒语一样有效

<input type="hidden" id="email" name="email" />

添加到这个线程,以防其他人有同样的问题。

最后,我找到了一个解决方案,很简单:

document.getElementById("texens").value = "tinkumaster";

效果非常好。不知道为什么jQuery没有退回到这一步。