在 HTML Select 选项中传递隐藏的输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1170386/
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-29 00:22:25  来源:igfitidea点击:

Passing hidden input fields in HTML Select option

htmlhiddenhtml-select

提问by Andy Birchall

Does anyone know if it's possible to pass a hidden request parameter in with a <select><option>element in a HTML form?

有谁知道是否可以将隐藏的请求参数与<select><option>HTML 表单中的元素一起传递?

So for example, if the user selected <option value="foo">foo</option>from a <select>list of options, could I somehow pass a hidden value in, as well as the "foo" value, and retrieve that as a request parameter? E.g. <input type="hidden" name="x" value="bar"/>would enable me to get the values "foo" and "bar" from the request when the user selected the foo option.

例如,如果用户<option value="foo">foo</option><select>选项列表中选择,我能否以某种方式传递一个隐藏值以及“foo”值,并将其作为请求参数检索?例如,<input type="hidden" name="x" value="bar"/>当用户选择 foo 选项时,我可以从请求中获取值“foo”和“bar”。

Thanks

谢谢

回答by Jeff Widmer

A select list has both a value that is displayed to the user and a value that is passed back to the server in the form post. So you could use some sort of delimiter in the posted value to get both values sent back and then parse them at that point:

选择列表既有显示给用户的值,也有在表单发布中传递回服务器的值。因此,您可以在发布的值中使用某种分隔符来发送两个值,然后在此时解析它们:

        <select id="myselectlist" >
            <option value="foo|bar">foo</option>
            <option value="foo2|bar2">foo2</option>
        </select>

But better yet would be to pass back an ID value which you could then use to know which item was selected from a database and also use it to look up the second related item:

但更好的是传回一个 ID 值,然后您可以使用它来了解从数据库中选择了哪个项目,并使用它来查找第二个相关项目:

        <select id="myselectlist" >
            <option value="123">foo</option>
            <option value="124">foo2</option>
        </select>

Your database might look like this:

您的数据库可能如下所示:

ID   DisplayValue   OtherData   
123  foo            bar     
124  foo2           bar2    

回答by Dave Anderson

There is the form input type='hidden'which you could update using the onchangeevent of the select drop down then it would be posted with the form. I suspect you would want to create an array of the possible values for the hidden input in the same order as their equivalents in the select drop down and then access the value in the array by index using the selectedIndexproperty of the select element.

有一个表单输入type='hidden',您可以使用onchange选择下拉列表的事件更新它,然后它将与表单一起发布。我怀疑您希望按照与 select 下拉列表中的等效项相同的顺序为隐藏输入创建一个可能值的数组,然后使用selectedIndexselect 元素的属性通过索引访问数组中的值。

回答by Garet Claborn

Here's an alternative solution assuming jQuery is available. If you use a js utility library other than jQuery, or no library at all, this is still possible. Its just binding a function to the select's onchange event and parsing the json from a custom data-attribute.

这是假设 jQuery 可用的替代解决方案。如果您使用 jQuery 以外的 js 实用程序库,或者根本没有库,这仍然是可能的。它只是将一个函数绑定到 select 的 onchange 事件并从自定义数据属性解析 json。

<form>
<select name="AnySelect">
 <option value="primary-value0" data-support='["test",128,2014,"blackberry"]' />
 <option value="primary-value1" data-support='["test1",39,2013,"apricot"]' />
 <option value="primary-value2" data-support='["test2",42,2012,"peach"]' />
 <option value="primary-value3" data-support='[null,null]' />
 <option value="primary-value4" data-support='[30,28,null]' />
</select>
.
.
.
<span style="visibility: hidden" id="Support_AnySelect-container"><span>
</form>

^Markup ------- JavaScript v

^标记 ------- JavaScript v

//bind onchange once document is loaded and ready
$.ready(function(){ $('#TheSelector').on('change',UpdateHidden); });

function UpdateHidden(event)
{
  //Create a base name for grouping dynamic values; ex: Support_AnySelect
  Name='Support_'+SelectField.attr('name');

  //Check if container was made for us already
  Contain=$(this.parent).find('#'+Name+'-container');

  if(Container.length===0)  //make the container if missing
  {
    $(this).after('<span id="'+Name+'-container" style="visibility: none;"></span>');
    Contain=$(this.parent).children('#'+Name+'-container');
  }

  //get our special multi-values, jQuery will auto decode the JSON
  SupportValues = this.data('support');

  Contain.empty(); //get rid of last select options
  $.each(SupportValues,function(i,val)
  {
    Contain.append('<input type="hidden" name="'+Name+'['+i+'] value="'+val+'"/>');
  });
}

Main benefit of this is that it should, in theory, let you post a 'variable amount of variables' from the form. You could also adjust the script to account for certain nested objects. As long as you pass in valid JSON to the data-attribute of your choice.

这样做的主要好处是,理论上,它应该让您从表单中发布“可变数量的变量”。您还可以调整脚本以考虑某些嵌套对象。只要您将有效的 JSON 传递给您选择的数据属性。

If anyone tries this out before I do, please let me know. I will test this later on but may have some minor errors.You should be able to use this on any select element and have hidden inputs automatically populate inside another element; script should also guarantee these to be in the same form tag for you and having unique but grouped names via HTTP array.

如果有人在我之前尝试过,请告诉我。我稍后会对此进行测试,但可能会有一些小错误。您应该能够在任何选择元素上使用它,并且隐藏输入会自动填充到另一个元素中;脚本还应保证这些为您使用相同的表单标签,并通过 HTTP 数组具有唯一但分组的名称。

回答by Foram Shah

If you need to use a hidden field for each options of the select dropdown, you can set that value in your own attribute in tag, instead of setting it into hidden field.

如果您需要为选择下拉列表的每个选项使用隐藏字段,您可以在标签中自己的属性中设置该值,而不是将其设置为隐藏字段。

<option value="foo" fooData="foo|bar">foo</option>
<option value="foo2" fooData="foo2|bar2">foo2</option>

回答by ChameleonCoder

I'd like to just add, that if you are willing to use radio buttons instead of a dropdown selection, the following worked for me:

我想补充一点,如果您愿意使用单选按钮而不是下拉选择,以下对我有用:

<label>Email:</label>


 {% for email in emails %}
 <input type="radio" id="{{ email.email_address }}" name="emaildata" value="{{ email.email_address }}">
 <label for="{{ email.email_address }}">{{ email.email_address }} </label>
 {% empty %}
 {% endfor %}

Then in your views, you still retrieve data same as above:

然后在您的视图中,您仍然检索与上述相同的数据:

email = request.POST.get("emaildata","")

Good Luck!

祝你好运!