JQuery:更改隐藏输入字段的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5289397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:54:41  来源:igfitidea点击:

JQuery: Change value of hidden input field

jqueryhidden-field

提问by helgatheviking

I'm having a hella time setting the value of a hidden input.

我正在设置隐藏输入的值。

I want to pass the HTML from between the option tags to the hidden field- end run it will the page title from wordpress' wp_list_dropdowns(). I've got it returning the text just fine, and on my change event it correctly adds some css (obviously unneeded on a hidden field, but I was trying to determine where things are breaking down). Works if I change the hidden input to a text input. I've seen in several places on SO that this is possible, (changing the value of a hidden input that is), but something is holding me up now and I can't see the answer.

我想将选项标签之间的 HTML 传递给隐藏的字段 - 端运行它将来自 wordpress' 的页面标题wp_list_dropdowns()。我已经让它很好地返回了文本,并且在我的更改事件中它正确地添加了一些 css(在隐藏字段上显然不需要,但我试图确定事情在哪里崩溃)。如果我将隐藏输入更改为文本输入,则有效。我已经在 SO 上的几个地方看到这是可能的(更改隐藏输入的值),但是现在有些东西阻碍了我,我看不到答案。

Here's the JSFiddle:

这是JSFiddle

JavaScript:

JavaScript:

$(".selector").change(function() {
    var $value = $(this).val();
    var $title = $(this).children('option[value='+$value+']').html();
    alert($title); 
    $('input#bacon').val($title).css('border','3px solid blue');
});

HTML:

HTML:

<select class="selector" name="testselect">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
</h3>

<input id="bacon" type="hidden" class="bacon" value="" name="testinput">

采纳答案by alex

Your jQuery code works perfectly. The hidden field isbeing updated.

您的 jQuery 代码运行良好。隐藏字段更新

回答by Yasir Aslam

It's simple as:

这很简单:

$('#action').val("1");

#actionis hidden input field id.

#action是隐藏的输入字段ID。

回答by Santosh Linkha

Seems to work

似乎工作

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

只需检查您的萤火虫。并且不要将 css 放在隐藏输入上。

回答by Joe Hyde

If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.

如果您在 Drupal 中执行此操作并使用 Form API 将 #type 从文本更改为 hook_form_alter 中的“隐藏”(例如),请注意输出 HTML 将具有不同(或省略)DIV 包装器、ID 和类名称。