Html 从多项选择中发布值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11616659/
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
Post values from a multiple select
提问by user1430949
How can I post values from a multiple select in a form? When I hit submit none of the selected values are posted.
如何从表单中的多项选择发布值?当我点击提交时,没有任何选定的值被发布。
<form id="form" action="" method="post">
<div>
<select id="inscompSelected" multiple="multiple" class="lstSelected">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="submit">
</div>
</form>
回答by iambriansreed
You need to add a name
attribute.
您需要添加一个name
属性。
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
由于这是一个多选,在 HTTP 级别,客户端只是发送多个具有相同名称的名称/值对,如果您使用带有method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
对于 PHP、Ruby 和其他一些库/框架,您需要[]
在名称末尾添加方括号 ( )。框架将解析该字符串并以某种易于使用的格式(如数组)呈现它。
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
除了手动解析请求之外,没有语言/框架/库不可知的方式来访问多个值,因为它们都有不同的 API
For PHP you can use:
对于 PHP,您可以使用:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
回答by Chin2
try this : here select is your select element
试试这个:这里选择是你的选择元素
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
数据采用查询字符串的形式 iename=value&name=anotherValue