我编写了以下代码来选择多个复选框,还需要验证至少选中了一个复选框。在以下代码中,如果我删除onsubmit="return validate_form()"
,则数据提交到数据库。但我想验证至少选中了一个复选框。
以下是代码:
<?php
$link=mysql_connect("localhost","root","") or die("cant connect");
mysql_select_db("country_ajax",$link) or die("cant select db");
extract($_POST);
$check_exist_qry="select * from language";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_language=explode(',',$my_value['language_name']);
}
if(isset($submit))
{
$fname=$_POST['fname'];
$sname=$_POST['sname'];
$all_language_value = implode(",",$_POST['language']);
if($total_found >0)
{
//update
$upd_qry="UPDATE language SET language_name='".$all_language_value."' where member_id = 75";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO language(language_name) VALUES('".$all_language_value."') where member_id = 75";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="" onsubmit="return validate_form()";>
<input type="text" name="fname"/><br>
<input type="text" name="sname"/><br>
languahe you know <br/>
<input type="checkbox" name="language[]" value="1" <?php if(in_array(1,$my_stored_language)){echo "checked";}?>><label>PHP</label><br>
<input type="checkbox" name="language[]" value="2" <?php if(in_array(2,$my_stored_language)){echo "checked";}?>><label>Java</label><br>
<input type="checkbox" name="language[]" value="3" <?php if(in_array(3,$my_stored_language)){echo "checked";}?>><label>c</label><br>
<input type="checkbox" name="language[]" value="4" <?php if(in_array(4,$my_stored_language)){echo "checked";}?>><label>javascript</label><br>
<input type="checkbox" name="language[]" value="5" <?php if(in_array(5,$my_stored_language)){echo "checked";}?>><label>c#</label><br>
<input type="checkbox" name="language[]" value="6" <?php if(in_array(6,$my_stored_language)){echo "checked";}?>><label>.net</label><br>
<input type="submit" name="submit" value="submit">
</form>
<script>
function validate_form()
{
valid = true;
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
return valid;
}
</script>
答案 0 :(得分:2)
function validate_form()
{
valid = true;
$('form').find('input[type=checkbox]').each(function(){
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
)};
return valid;
}
试试这个。