If you include an interest grouping in your sign-up form using checkboxes, you may want to enforce your visitors to select at least one interest.
There are multiple ways to go about this. As a start, you can pre-select one of the choices. To do this, you can add a “checked” attribute to the input field which you want to preselect.
Pre-select an option
In the following example, the input field for “Group 2” has an additional checked
attribute. This will preselect that option when the page is loaded.
<p>
<label>Checkbox Groups</label>
<label>
<input name="INTERESTS[c503c0f57d][]" type="checkbox" value="0f8a0ed3bd"> <span>Group 1</span><br />
</label>
<label>
<input name="INTERESTS[c503c0f57d][]" type="checkbox" value="9446882237" checked> <span>Group 2</span><br />
</label>
<label>
<input name="INTERESTS[c503c0f57d][]" type="checkbox" value="c12429b8e8"> <span>Group 3</span><br />
</label>
</p>
Use JavaScript to require at least 1 selection
Another option is to use the following piece of JavaScript in your sign-up form. Whenever the form is submitted, this piece of code will ensure that at least one interest grouping was selected.
<script>
jQuery('.mc4wp-form').on('change', function(evt) {
let checkboxFields = jQuery(this).find('[name^="INTERESTS"]');
let checkedCount = checkboxFields.filter(':checked').length;
checkboxFields.prop('required', checkedCount == 0);
});
</script>
Of course you can also combine the above two methods. A complete example can be found in our sample code snippets repository on GitHub.