验证复选框-不检测它'选中

Validating Checkboxes - Not detecting it's checked

本文关键字:选中 检测 复选框 验证      更新时间:2023-09-26

我一整天都在纠结这个问题。除了复选框之外,所有其他验证都可以正常工作。它似乎验证了它,但没有检测到什么时候检查。意思是,我选中一个方框,它仍然会让我输入联系时间,不管我选中哪个方框。请帮助! !

只是那个选择最佳时间联系你的那个出了问题。

下面是我的复选框:

<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>

我的验证码:

    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;
} 

由于您有多个具有相同名称的元素,因此document.rental.best_contact_time将是NodeList而不是HTMLElementNode。

您需要循环遍历列表(将其视为数组)并依次检查每个列表