javascript 如何发布选择列表中的所有选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15190464/
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
How do I POST all options in a select list?
提问by Steve
I have a select multiple list that has a few items in it. It is a list of IP addresses for an ACL. People can add/remove IPs, and then save the list. However, unless you select an item on the list, $_POST[selectName]
does not contain any values. How can I accomplish this? I know I can do this with javascript but I would rather stick to PHP.
我有一个选择多个列表,其中包含一些项目。它是 ACL 的 IP 地址列表。人们可以添加/删除 IP,然后保存列表。但是,除非您选择列表中的一项,否则$_POST[selectName]
不包含任何值。我怎样才能做到这一点?我知道我可以用 javascript 做到这一点,但我宁愿坚持使用 PHP。
回答by Kamil
Edit/corrected: You need JS. There is no way to send all (selected and not selected) options via POST. You have to programatically select all options before submission.
编辑/更正:您需要 JS。无法通过 POST 发送所有(选中和未选中)选项。您必须在提交之前以编程方式选择所有选项。
File with form (file1.php):
带表单的文件(file1.php):
<script type="text/javascript">
function selectAll()
{
selectBox = document.getElementById("someId");
for (var i = 0; i < selectBox.options.length; i++)
{
selectBox.options[i].selected = true;
}
}
</script>
<form method="post" action="file2.php">
<select id="someId" name="selectName[]" multiple>
<option value="123.123.123.123">123.123.123.123</option>
<option value="234.234.234.234">234.234.234.234</option>
</select>
<input type="submit" name="submit" value=Submit onclick="selectAll();">
</form>
File that receives POST (file2.php):
接收 POST 的文件(file2.php):
<?php
foreach ($_POST['selectName'] as $item)
{
print "$item<br/>";
}
?>
回答by RestlessWeb
Just to tack on this you could also use the jQuery version of @Kamil's code which is a little simpler than the loop:
为了解决这个问题,您还可以使用@Kamil 代码的 jQuery 版本,它比循环简单一点:
<script type="text/javascript">
jQuery('[name="form1"]').on("submit",selectAll);
function selectAll()
{
jQuery('[name="selectName[]"] option').prop('selected', true);
}
</script>
<form name="form1" method="post" action="file2.php">
<select id="someId" name="selectName[]" multiple>
<option value="123.123.123.123">123.123.123.123</option>
<option value="234.234.234.234">234.234.234.234</option>
</select>
<input type="submit" name="submit" value=Submit onclick="selectAll();">
</form>