使用 jQuery 的“.val()”设置表单中隐藏字段的值不起作用

发布于 2024-09-04 22:11:38 字数 939 浏览 11 评论 0原文

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

这是解释该问题的示例代码。如果我将输入类型保留为“文本”,则它可以正常工作。但是,将输入类型更改为“隐藏”是行不通的!

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

我还尝试了以下解决方法,将输入类型设置为“文本”,然后对输入框使用“display:none”样式。但是,这也失败了! 看起来 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>

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

初见 2024-09-11 22:11:38

对于类型值为 hidden 的输入,:text 将失败。使用它也更有效:

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

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

示例位于 http://jsbin.com/elovo/edit,使用 http://jsbin.com/elovo/2/edit

: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

莫言歌 2024-09-11 22:11:38

如果您在设置隐藏字段的值时遇到问题,因为您要向其传递 ID,则可以使用以下解决方案:

而不是 $("#hidden_​​field_id").val(id)执行$("input[id=hidden_​​field_id]").val(id)。不确定有什么区别,但它有效。

If you're having trouble setting the value of a hidden field because you're passing an ID to it, this is the solution:

Instead of $("#hidden_field_id").val(id) just do $("input[id=hidden_field_id]").val(id). Not sure what the difference is, but it works.

脸赞 2024-09-11 22:11:38

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

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

效果很好。不知道为什么 jQuery 不回退到这个。

Finally, I have found a solution and it's a simple one:

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

Works like a charm. No clue why jQuery does not fall back to this.

摘星┃星的人 2024-09-11 22:11:38

我有同样的问题。奇怪的是,谷歌浏览器和可能其他人(不确定)不喜欢

$("#thing").val(0);

input type="hidden" id="thing" name="thing" value="1" />

(没有变化)

$("#thing").val("0");

input type="hidden" id="thing" name="thing" value="1" />

(没有变化),

但这有效!!!!

$("#thing").val("no");

input type="hidden" id="thing" name="thing" value="no" />

改变!

$("#thing").val("yes");

input type="hidden" id="thing" name="thing" value="yes" />

改变!

一定是一个“字符串的东西”

I had same problem. oddly enough google chrome and possibly others (not sure) did not like

$("#thing").val(0);

input type="hidden" id="thing" name="thing" value="1" />

(no change)

$("#thing").val("0");

input type="hidden" id="thing" name="thing" value="1" />

(no change)

but this works!!!!

$("#thing").val("no");

input type="hidden" id="thing" name="thing" value="no" />

CHANGES!!

$("#thing").val("yes");

input type="hidden" id="thing" name="thing" value="yes" />

CHANGES!!

must be a "string thing"

盛夏已如深秋| 2024-09-11 22:11:38
$('input[name=hidden_field_name]').val('newVal');

为我工作,但既没有

$('input[id=hidden_field_id]').val('newVal');

$('#hidden_field_id').val('newVal');

没有。

$('input[name=hidden_field_name]').val('newVal');

worked for me, when neither

$('input[id=hidden_field_id]').val('newVal');

nor

$('#hidden_field_id').val('newVal');

did.

天涯沦落人 2024-09-11 22:11:38

.val 对我不起作用,因为我正在获取服务器端的值属性并且该值并不总是更新。所以我用了:

var counter = 0;
$('a.myClickableLink').click(function(event){
   event.preventDefault();
   counter++;

   ...
   $('#myInput').attr('value', counter);
}

希望它能帮助别人。

.val didnt work for me, because i'm grabbing the value attribute server side and the value wasn't always updated. so i used :

var counter = 0;
$('a.myClickableLink').click(function(event){
   event.preventDefault();
   counter++;

   ...
   $('#myInput').attr('value', counter);
}

Hope it helps someone.

飘过的浮云 2024-09-11 22:11:38

事实上,这是一个持续存在的问题。虽然 Andy 对下载的源代码的看法是正确的,但 .val(...) 和 .attr('value',...) 似乎并没有真正修改 html。我认为这是一个 javascript 问题,而不是一个 jquery 问题。如果你使用过 firebug,你也会有同样的问题。虽然看起来如果您提交带有修改后的值的表单,它将通过,但 html 不会更改。我在尝试创建修改后的表单的打印预览(执行 [form].html())时遇到了这个问题,它可以正常复制所有内容,包括除值更改之外的所有更改。因此,我的模式打印预览有点无用......我的解决方法可能必须是“构建”一个包含他们添加的值的隐藏表单,或者独立生成预览并使用户所做的每次修改也修改预览。两者都不是最佳的,但除非有人弄清楚为什么值设置行为不会改变 html(我假设在 DOM 中),否则它必须这样做。

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.

梦屿孤独相伴 2024-09-11 22:11:38

我遇到了同样的问题,我发现出了什么问题。我将 HTML 定义为

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

读取服务器上的表单值总是导致电子邮件为空。在挠头(和大量搜索)之后,我意识到错误是没有正确定义表单/输入。在修改输入时(如下所示),它就像一个魅力

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

添加到此线程,以防其他人遇到相同的问题。

I was having the same issue, and I found out what was wrong. I had the HTML defined as

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

Reading the form values on server always resulted in email as empty. After scratching my head (and numerous search), I realized the mistake was not defining the form/input correctly. On modifing the input (as shown next), it worked like a charm

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

Adding to this thread in case others have the same issue.

夏末的微笑 2024-09-11 22:11:38

就我而言,我使用非字符串(整数)作为 val() 的参数,这不起作用,技巧很简单

$("#price").val('' + price);

In my case, I was using a non-string (integer) as the parameter of val() which doesn't work, the trick is just as simple as

$("#price").val('' + price);
青芜 2024-09-11 22:11:38

使用 val() 对我来说不起作用。我必须在任何地方使用 .attr() 。此外,我有不同类型的输入,并且在复选框和选择菜单的情况下必须非常明确。

更新文本字段

$('#model_name').attr('value',nameVal);

更新文件输入旁边的图像

$('#img-avatar').attr('src', avatarThumbUrl);

更新布尔值

if (isActive) {
    $('#model_active').attr('checked',"checked");
} else {
    $('#model_active').attr('checked', null) ;
}

更新选择(使用数字或字符串)

$('#model_framerate').children().each(function(i, el){
    var v = $(el).val();
    if (v === String(framerateVal)) { 
        $(el).attr('selected','selected');
    } else {
        $(el).attr('selected',null);
    }
}

Using val() didn't work for me. I had to use .attr() everywhere. Also I had different types of inputs and had to be pretty explicit in the case of check boxes and select menus.

Update textfield

$('#model_name').attr('value',nameVal);

Update image next to file input

$('#img-avatar').attr('src', avatarThumbUrl);

Update boolean

if (isActive) {
    $('#model_active').attr('checked',"checked");
} else {
    $('#model_active').attr('checked', null) ;
}

Update select (with number or string)

$('#model_framerate').children().each(function(i, el){
    var v = $(el).val();
    if (v === String(framerateVal)) { 
        $(el).attr('selected','selected');
    } else {
        $(el).attr('selected',null);
    }
}
青巷忧颜 2024-09-11 22:11:38

这里的另一个问题浪费了我的一些时间,所以我想我会传递这个提示。我有一个隐藏字段,我给了一个 id 。名称中的 [] 括号(由于与 struts2 一起使用)和选择器 $("#model.thefield[0]") 找不到我的隐藏字段。将 id 重命名为不使用句点和括号会导致选择器开始工作。所以最后我得到了一个 id model_the_field_0 而选择器工作正常。

Another gotcha here wasted some of my time, so I thought I would pass along the tip. I had a hidden field I gave an id that had . and [] brackets in the name (due to use with struts2) and the selector $("#model.thefield[0]") would not find my hidden field. Renaming the id to not use the periods and brackets caused the selector to begin working. So in the end I ended up with an id of model_the_field_0 instead and the selector worked fine.

早茶月光 2024-09-11 22:11:38

如果您正在搜索 haml,那么这就是隐藏字段将值设置为隐藏字段的答案,例如

%input#forum_id.hidden

在您的 jquery 中,只需将值转换为字符串,然后使用 jquery 中的 attr 属性附加它。希望这也适用于其他语言。

$('#forum_id').attr('val',forum_id.toString());

If you are searching for haml then this is the answer for hidden field to set value to a hidden field like

%input#forum_id.hidden

In your jquery just convert the value to string and then append it using attr property in jquery. hope this also works in other languages also.

$('#forum_id').attr('val',forum_id.toString());
晨敛清荷 2024-09-11 22:11:38

使用 ID:

$('input:hidden#texens').val('tinkumaster');

使用类:

$('input:hidden.many_texens').val('tinkumaster');

Using ID:

$('input:hidden#texens').val('tinkumaster');

Using class:

$('input:hidden.many_texens').val('tinkumaster');
临风闻羌笛 2024-09-11 22:11:38

在迷失在本页上的无数答案之后,没有一个真正起作用,我找到了如何在我的案例中做到这一点。

由于某种原因,在选择器中使用 input 并没有做到这一点。我在表单元素上没有 ID,因此无法对选择器使用任何 ID。即使我这样做了,我也很确定它不会起作用。

这是我的解决方案:

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

本质上,选择任何名称为“something”的元素。试一试。

After getting lost in the myriad answers on this page, none of which actually worked, I found out how to do this in my case.

For some reason using input in the selector was not doing it. I did not have an ID on the form element so I couldn't use any IDs for selectors. And even if I did I'm pretty sure it wouldn't have worked.

Here's my solution:

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

Essentially, select any element with the name of "something". Give it a shot.

沉睡月亮 2024-09-11 22:11:38

尝试了所有方法后,devtools 显示他们更改了 id,这有效:

$("#form-field-{field_id}").value('free');

After trying everything, devtools shows that they changed the id, this worked:

$("#form-field-{field_id}").value('free');
梅倚清风 2024-09-11 22:11:38
<javascript>


slots=''; hidden=''; basket = 0;

    cost_per_slot = $("#cost_per_slot").val();
    //cost_per_slot = parseFloat(cost_per_slot).toFixed(2)

    for (i=0; i< check_array.length; i++) {
        slots += check_array[i] + '\r\n';
        hidden += check_array[i].substring(0, 8) + '|';
        basket = (basket + parseFloat(cost_per_slot));
    }

    // Populate the Selected Slots section
    $("#selected_slots").html(slots);

    // Update hidden slots_booked form element with booked slots
    $("#slots_booked").val(hidden);     

    // Update basket total box
    basket = basket.toFixed(2);
    $("#total").html(basket);

<javascript>


slots=''; hidden=''; basket = 0;

    cost_per_slot = $("#cost_per_slot").val();
    //cost_per_slot = parseFloat(cost_per_slot).toFixed(2)

    for (i=0; i< check_array.length; i++) {
        slots += check_array[i] + '\r\n';
        hidden += check_array[i].substring(0, 8) + '|';
        basket = (basket + parseFloat(cost_per_slot));
    }

    // Populate the Selected Slots section
    $("#selected_slots").html(slots);

    // Update hidden slots_booked form element with booked slots
    $("#slots_booked").val(hidden);     

    // Update basket total box
    basket = basket.toFixed(2);
    $("#total").html(basket);

幸福还没到 2024-09-11 22:11:38

只需使用 get 和 set 下面的语法

GET

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

这里变量将保存隐藏字段(selectindex)的值

服务器端

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

设置

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

Simply use syntax below get and set

GET

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

here a variable will hold the value of hiddenfield(selectindex)

Server side

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

SET

var a =10;
$("#selectIndex").val(a);
如梦亦如幻 2024-09-11 22:11:38

对于任何其他正在为此苦苦挣扎的人,有一种非常简单的“内联”方法可以使用 jQuery 来执行此操作:

<input type="search" placeholder="Search" value="" maxlength="256" id="q" name="q" style="width: 300px;" onChange="$('#ADSearch').attr('value', $('#q').attr('value'))"><input type="hidden" name="ADSearch" id="ADSearch" value="">

当使用 onChange 事件将文本键入到可见输入时,这会设置隐藏字段的值。当您想要将字段值传递到“高级搜索”表单而不强迫用户重新输入搜索查询时,这很有用(就像我的情况一样)。

Anyone else who is struggling with this, there is a very simple "inline" way to do this with jQuery:

<input type="search" placeholder="Search" value="" maxlength="256" id="q" name="q" style="width: 300px;" onChange="$('#ADSearch').attr('value', $('#q').attr('value'))"><input type="hidden" name="ADSearch" id="ADSearch" value="">

This sets the value of the hidden field as text is typed into the visible input using the onChange event. Helpful (like in my case) where you want to pass on a field value to an "Advanced Search" form and not force the user to re-type their search query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文