这是我的代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="form-si-hasil.php" method="post" onsubmit="return validate(this)" id="form" name="form">
<h1>Form Hobi</h1>
<input type="checkbox" name="ck1" value="Membaca" id="checkbox1">Membaca
<br />
<input type="checkbox" name="ck2" value="Sport" id="checkbox2">Sport
<br />
<input type="checkbox" name="ck3" value="Singing" id="checkbox3">Singing
<br />
<input type="checkbox" name="ck4" value="Dancing" id="checkbox4">Dancing
<br />
<br />
<input type="submit">
</form>
<script src="../js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" language="JavaScript">
function validate(){
var pilihan1 = document.getElementById("checkbox1").checked;
if(pilihan1=="") {
alert("Checkbox pertama tidak boleh kosong");
return false
}
return true
}
</script>
</body>
</html>
答案 0 :(得分:1)
试试这个 -
<script type="text/javascript" language="JavaScript">
function validate(){
var pilihan1 = document.getElementById("checkbox1").checked;
var pilihan2 = document.getElementById("checkbox2").checked;
var pilihan3 = document.getElementById("checkbox3").checked;
var pilihan4 = document.getElementById("checkbox4").checked;
var flag =0;
if(pilihan1=="") {
alert("Checkbox pertama tidak boleh kosong");
flag=0;
}
else if(pilihan2=="") {
alert("Checkbox 2");
flag=0;
}
else if(pilihan3=="") {
alert("Checkbox 3");
flag=0;
}
else if(pilihan4=="") {
alert("Checkbox 4");
flag=0;
} else {
flag=1;
}
if(flag==1){
return true;
} else {
return false;
}
</script>
答案 1 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
var isCheck = $(this).prevAll("input").is(":checkbox");
var total = $(this).prevAll("input[type='checkbox']").length;
var checkTotal = $(this).prevAll("input[type='checkbox']:checked").length;
if(isCheck && ((total-checkTotal)>1)){
$(this).prop("checked",false);
alert("false");
}else{
alert("ture");
}
});
});
</script>
</head>
<body>
<form action="form-si-hasil.php" method="post" onsubmit="return validate(this)" id="form" name="form">
<h1>Form Hobi</h1>
<input type="checkbox" name="ck1" value="Membaca" id="checkbox1">Membaca
<br />
<input type="checkbox" name="ck2" value="Sport" id="checkbox2">Sport
<br />
<input type="checkbox" name="ck3" value="Singing" id="checkbox3">Singing
<br />
<input type="checkbox" name="ck4" value="Dancing" id="checkbox4">Dancing
<br />
<input type="checkbox" name="ck4" value="Dancing" id="checkbox4">test
<br />
<input type="checkbox" name="ck4" value="Dancing" id="checkbox4">test 1
<br />
<br />
<input type="submit">
</form>
</body>
</html>