Search code examples
javascriptjqueryhtmlcheckboxrequired

Form with checkbox that is required to continue (if not displays an error)


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

  • 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.