如何在php中获取选择框的多个选定值?

给定项目列表, 任务是使用PHP从选择框中检索多个选择的值。

在HTML中使用Multiple属性从下拉列表中选择多个值。在HTML中选择多个值取决于操作系统和浏览器。

  • 对于窗口用户–按住+ CTRL键选择多个选项
  • 对于Mac用户-按住Command键可选择多个选项

例子:本示例使用HTML创建项目列表。

<html>

<body>

<form method = "post" action = "name.php">

<h4>SELECT SUJECTS</h4>

<!--Using multiple to select multiple value-->

<select name = "subject" multiple size = 6>

<option value = "english">ENGLISH</option>

<option value = "maths">MATHS</option>

<option value = "computer">COMPUTER</option>

<option value = "physics">PHYSICS</option>

<option value = "chemistry">CHEMISTRY</option>

<option value = "hindi">HINDI</option>

</select>

<input type = "submit" name = "submit" value = Submit>

</form>

</body>

</html>

现在, 任务是从列表中检索或打印多个选定的值。使用表单方法和循环来检索PHP中的选定值。

例子:

<html>

<body>

<!--name.php to be called on form submission-->

<form method = 'post'>

<h4>SELECT SUJECTS</h4>

<select name = 'subject[]' multiple size = 6>

<option value = 'english'>ENGLISH</option>

<option value = 'maths'>MATHS</option>

<option value = 'computer'>COMPUTER</option>

<option value = 'physics'>PHYSICS</option>

<option value = 'chemistry'>CHEMISTRY</option>

<option value = 'hindi'>HINDI</option>

</select>

<input type = 'submit' name = 'submit' value = Submit>

</form>

</body>

</html>

<?php

//Check if form is submitted successfully

if (isset( $_POST [ "submit" ]))

{

//Check if any option is selected

if (isset( $_POST [ "subject" ]))

{

//Retrieving each selected option

foreach ( $_POST [ 'subject' ] as $subject )

print "You selected $subject<br/>" ;

}

else

echo "Select an option first !!" ;

}

?>

输出如下:

图片

注意:该表格可以使用$ _GET方法。这取决于form方法=”?”值。

以上是 如何在php中获取选择框的多个选定值? 的全部内容, 来源链接: utcz.com/p/202648.html

回到顶部