我正在寻找一种方法来告诉用户,如果他按下提交按钮而没有选择任何复选框,他必须至少选择一个复选框。通过使用php
<?php
if(isset($_POST['submit']))
{
$checked=0;
for($i=0;$i<=2;$i++){//check all the boxes
if(isset($_POST['checkbox'.$i]))
$checked=1;
}
}
if ($checked==0){//alert if no boxes are checked
echo("You must check at least 1");
}
else{
header("location: nextpage.php");
}
?>
<form name="form1" method="POST" action="">
<input name="checkbox0" type="checkbox" value="1"> 1
<input name="checkbox1" type="checkbox" value="2"> 2
<input name="checkbox2" type="checkbox" value="3"> 3
<input name="submit" type="submit" value="Submit">
</form>
您可以使用@jm-verstigue-answer将用户重定向到您想要的页面:
if ($checked == 0){
// display alert
} else {
// redirect user
}
PHP发生在服务器上,在用户看到页面之前。用户只能看到最终渲染的产品。您可以使用javascript在元素离开页面之前测试元素是否被选中,或者在下一个处理表单的页面上测试它。(或者两者都做,因为javascript可以被用户关闭。)
您要查找的JS的开头是onsubmit()
,可能还有document.getElementByID['the id of the input field'].checked
如果您想在PHP中使用它,您可以执行:
<?php
if(isset($_POST['SubmitButton'])) //checking if form was submitted
{
if( isset($_POST['test'] )) //checking if button was checked
{
echo "Checkbox was checked!";
}
}
?>
<form action="" method="post">
<input type="checkbox" name="test" value="value">
<input type="submit" name="SubmitButton"/>
</form>
这将检查表单是否已提交,然后检查复选框是否已选中。如果是的话,那么它只是呼应了这个信息。很简单。
希望这能有所帮助。
我会为此使用Jquery,并这样做…
<form id="test" method="post" action="wherever.php">
<input type="checkbox" id="checkbox1" name="test" value="Checkbox1">Checkbox1
<button id="formsubmit">SUBMIT</button>
</form>
然后在您的Jquery中,执行
$('#formsubmit').click(function(e){
e.preventDefault();
if($("#checkbox1").is(':checked')){
//on success
$('form#test').submit();
} else {
//on no checkbox
alert('you need to check box');
}
});
此处演示