put this code in your <head> :-
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function IsTermChecked() {
if (!$("input:checkbox").is(":checked")) {
alert("You must agree to the terms of service.");
return false;
}
else
return true;
}
</script>
</head>
Also call the function IsTermChecked() on submit click :-
<input type="submit" role="button" value="Donate" class="btn btn-danger" onclick="return IsTermChecked();">
You have to use jquery library to user jQuery's functions. Try this. This will work definitely.
Form with checkbox that is required to continue (if not displays an error)
-
10-06-2023 - |
Question
Alright so basically I have a form that i added a checkbox to (agree to terms of service check box) anyways i need to make it so that it needs to be checked to continue with the donation process... I only have the HTML code i have no idea how to make this work.. Also if not checked i want a javascript alert to pop up displaying the error "You must agree to the terms of service".
Heres my HTML code
<form method="POST">
<!-- Add ranks with a new value on the next line! -->
<select name="rank">
<option value="1">Donator ($1.20)</option>
<option value="2">Moderator ($5.00)</option>
<option value="3">Administrator ($13.37)</option>
<option value="4">Super-Administrator ($33.00)</option>
</select>
<br />
<br />
<input type="checkbox" name="required">I agree to the <a href="/donate/tos/"> terms of service</a>.<br /><br />
<input type="submit" role="button" type="submit" value="Donate" class="btn btn-danger">
</form>
I'm pretty sure this is done with javascript except i have very very little experience with javascript & wouldn't know how to accomplish this
Solution
OTHER TIPS
You could disable the submit button then enable it when the checkbox is checked:
HTML
<form method="POST">
<!-- Add ranks with a new value on the next line! -->
<select name="rank">
<option value="1">Donator ($1.20)</option>
<option value="2">Moderator ($5.00)</option>
<option value="3">Administrator ($13.37)</option>
<option value="4">Super-Administrator ($33.00)</option>
</select>
<input type="checkbox" name="required">I agree to the <a href="/donate/tos/">terms of service</a>.<br />
<input type="submit" disabled role="button" type="submit" value="Donate" class="btn btn-danger">
</form>
Javascript
$("input[name='required']").click(function(){
$("input[type='submit']").prop("disabled", !this.checked);
});
JS Fiddle: http://jsfiddle.net/Q2kft/2/
To display the alert use the following:
$("input[type='submit']").click(function(e){
if($("input[name='required']:checked").length == 0){
e.preventDefault();
alert("You must check the input");
}
});
JS Fiddle: http://jsfiddle.net/Q2kft/1/
$(document).ready(function() {
$("form").submit(function() {
if (!$(this).find(":checkbox[name=required]").is(":checked")) {
alert ("You must agree to the terms of service.");
return false;
}
});
});