gpt4 book ai didi

javascript - jQuery 验证至少选择一个复选框

转载 作者:行者123 更新时间:2023-12-02 16:10:50 25 4
gpt4 key购买 nike

我编写了以下代码来选择多个复选框,并且还需要验证至少选择了一个复选框。在以下代码中,如果我删除 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>

最佳答案

    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;
}

试试这个。

关于javascript - jQuery 验证至少选择一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com