So, how do we do it?
Here’s what we came up with:
var found_checked = false;
// Loop through checkboxes and see if any have been selected
found_checked = true;
// Stop form submission if necessary
alert("You must select at least one class.");
Let’s take a closer look at a few lines of code and explain how they work:
- Line 3 – This will run our code when the user clicks on a webpage button with the id “form-submit”
- Line 5 – We declare a variable (“found_checked”) that is used later in the snippet to see whether any checkbox was selected
- Line 7 – We loop through all of the input fields (checkboxes) that are within a container called “.class-dates”
- Lines 9-13 – If a checkbox is selected, we set our variable to true and break out of the loop
- Lines 16-20 – If our variable is still set to false, that means no checkbox was selected, so we should abort the submission request with event.preventDefault()
Pretty simple overall, and our client was very happy with the results!
The event.preventDefault() method is compatible with all modern browsers, however Internet Explorer 8 and below are not supported.
It is possible to use a variable called event.returnValue if you need to ensure proper functioning in older browsers, though it should be noted that our example code relies on the jQuery library, which is also incompatible with IE8. Luckily, this version of Internet Explorer only accounts for 0.4% of the worldwide browser market share, so compatibility is not essential for most projects.
Questions? We’re here to help.
If you have any questions or would like to enlist our help in writing custom scripts for your website, feel free to contact us here. Together, we’ll bring your ideas to life.