在HTML表单中使用多选按钮,如何使多选按钮的值传到php中,显示在浏览器上
在HTML表单中使用多选按钮,可以通过使用<input>
标签中的type="checkbox"
属性来创建多选按钮。为了将所选值传递到PHP并显示在浏览器上,可以按照以下步骤进行操作:
<input type="checkbox" name="fruit[]" value="apple"> Apple<br>
<input type="checkbox" name="fruit[]" value="banana"> Banana<br>
<input type="checkbox" name="fruit[]" value="orange"> Orange<br>
在这里,name="fruit[]"
指定了一个名为“水果”的多选组,并用[]
告诉浏览器将所选值作为数组传递给PHP。
<form method="post" action="submit.php">
<input type="checkbox" name="fruit[]" value="apple"> Apple<br>
<input type="checkbox" name="fruit[]" value="banana"> Banana<br>
<input type="checkbox" name="fruit[]" value="orange"> Orange<br>
<input type="submit" value="Submit">
</form>
在此示例中,表单将使用POST方法提交,并将所选的多选按钮值提交到“submit.php”文件。
<?php
if(isset($_POST['fruit'])) {
$selected_fruits = $_POST['fruit'];
foreach ($selected_fruits as $fruit) {
echo $fruit . "<br>";
}
}
?>
在此示例中,$_POST['fruit']
将获取所选的多选按钮值,并以数组形式存储在$selected_fruits
变量中。然后,使用foreach循环遍历数组,并将每个所选项显示在浏览器上。
以上是一个简单的例子,可以根据具体需求进行修改。