Matt U
Matt U

Reputation: 46

Validating if a checkbox or radio button has been checked

The following function detects inputs with the class "required" and checks if they're empty before triggering the submit button and Google ReCAPTCHA.

function validate(event) {
event.preventDefault();
//
var questions = document.getElementsByClassName('required');
var valid = true;

for (var i=0; valid && i<questions.length; i++) {
    if (!questions[i].value.trim()) {
        valid = false;
    }
}
if (valid) {
    grecaptcha.execute();
} else {
    alert("Please fill out all required fields.");
}}

I'm trying to add a way to detect if a checkbox and/or radio button has been checked off as well.

Any ideas?

Upvotes: 0

Views: 41

Answers (1)

tymeJV
tymeJV

Reputation: 104775

You can check the type property on the element.

for (var i=0; valid && i<questions.length; i++) {
    if (questions[i].type === "checkbox") {
        valid = questions[i].checked;
    } else {
        if (!questions[i].value.trim()) {
            valid = false;
        }
    }

    if (!valid) break;
}

Upvotes: 1

Related Questions