Validate Multiple Checkbox Using Javascript

Case: User should choose at least one option on the checkbox.

Here is the code:

<form role="form" action="/admin/save" method="POST" onsubmit="return Validate()" id="edituser">
    <div class="form-group">
        <label>Role</label>&nbsp;&nbsp;&nbsp;&nbsp;<span id="errorMsg" class="msg"></span>
        <div class="checkbox" >
            <label>
                <input name="userRoles" type="checkbox" value="ROLE_ADMIN" >Admin
            </label>
        </div>
        <div class="checkbox" >
            <label>
                <input name="userRoles" type="checkbox" value="ROLE_USER"/>User
            </label>
        </div>
        <div class="checkbox" >
            <label>
                <input name="userRoles" type="checkbox" value="ROLE_VERIFICATOR" />Verificator
            </label>
        </div>
    </div>
</form>

<!-- js -->
<script>
    function check_checkboxes()
    {
        var c = document.getElementsByName('userRoles');
        for (var i = 0; i < c.length; i++)
        {
            if (c[i].checked) {
                return true;
            }
        }
        return false;
    }

    function Validate()
    {
        if (!check_checkboxes())
        {
            document.getElementById("errorMsg").innerText = "*Please choose at least one role";
            return false;
        }
        document.getElementById("errorMsg").innerText = "";
        return true;
    }

</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s