验证多个下拉菜单

时间:2012-11-30 12:56:22

标签: javascript validation

我在我的网络电子邮件表格中有四个下拉列表,如下所示

<select  name="newstaff"  class="formStyle" style="width:335px;" >
<option value="N/A">Please Select</option>
---- other options ---
<select name="allstaff"  class="formStyle" style="width:335px;" >
<option value="N/A">Please Select</option>
 ---- other options ---
<select  name="learning"  class="formStyle" style="width:400px;" >
<option value="N/A">Please Select</option>
---- other options ---
<select  name="leaders"  class="formStyle" style="width:335px;" >
<option value="N/A">Please Select</option>
---- other options ---

如果用户尝试提交此表单而未从至少一个下拉菜单“N / A

中选择至少一个其他选项,我将如何编写一个提示警报的验证函数

感谢

修改

用于验证表单的代码:

function validateForm(objForm)
{
    var returnStatus = 1;

    if (objForm.newstaff.selectedIndex == 0) {
        alert("please make a selection!");
        returnStatus = 0;
    };
    if (returnStatus) {
        objForm.submit();
    }
}

1 个答案:

答案 0 :(得分:1)

你很亲密。这里的区别在于获取标记名为select的元素数组。

validateForm = function(objForm) {
    var i = 0,
        valid = false,
        elements = objForm.getElementsByTagName("select");

    for ( ; i < elements.length; i++) {
        if (elements[i].selectedIndex) {
            valid = true;
            break;
        }
    }

    if (valid === true) {
        objForm.submit();
    } else {
        alert ("Please make a selection!");
    }
}