ALayton
ALayton

Reputation: 11

Validating Checkboxes - Not detecting it's checked

I've been struggling over this all day. All the other validation works fine except for the check boxes. It seems to validate it but doesn't detect when things are checked. Meaning, I'll check a box and it'll still say to enter in a contact time, no matter what box I check. Please help!!

Its just the one for selecting the best time to contact you that's acting up.

Here's my check boxes:

<input id="best_contact_time" name="best_contact_time" value="Morning 7-12" class="inputCheckbox" type="checkbox">Morning (7-12)<br>
<input id="best_contact_time" name="best_contact_time" value="Afternoon 12-5" class="inputCheckbox" type="checkbox">Afternoon (12-5)<br>
<input id="best_contact_time" name="best_contact_time" value="Evening 5-9" class="inputCheckbox" type="checkbox">Evening (5-9)<br>

And my validation code:

    function submitme() {
    // Validate required fields
    if (get_element('lastname').value == '') {
        alert('Please enter your last name');
        return false;
    }
    if (get_element('first_name').value == '') {
        alert('Please enter your first name');
        return false;
    }
    if (get_element('phone').value == '') {
        alert('Please enter a phone number');
        return false;
    }

    if (get_element('email').value == '') {
        alert('Please enter an email address');
        return false;
    }

    var ischecked = 0;
        for (var i = 0; i < document.rental.best_contact_time.length; i++) {
            var e = document.rental.best_contact_time;
            if (e.checked == true)
            { ischecked = 1; }
        }
        if (ischecked == 0) {
            alert('Please enter the best time to contact you');
            return false;
        }



    if (get_element('approximate_start_date').value == '') {
        alert('Please enter an approximate start date');
        return false;

    }



    document.forms[0].submit();
    return true;
} 

Upvotes: 1

Views: 302

Answers (1)

Quentin
Quentin

Reputation: 944010

Since you have multiple elements with the same name, document.rental.best_contact_time will be a NodeList not an HTMLElementNode.

You would need to loop through the list (treat it like an array) and check each one in turn.

Upvotes: 2

Related Questions