我有一个包含多个必填字段的表单,除了下拉列表之外,所有这些字段都有效。
我使用此代码来检查字段:
function formCheck(formobj){
// Enter name of mandatory fields
var fieldRequired = Array("name", "country", "email", "tel");
// Enter field description to appear in the dialog box
var fieldDescription = Array("Name", "Country", "Email", "Telephone");
// dialog message
var alertMsg = "Please complete the following fields:\n";
var l_Msg = alertMsg.length;
for (var i = 0; i < fieldRequired.length; i++){
var obj = formobj.elements[fieldRequired[i]];
if (obj){
switch(obj.type){
case "select-one":
if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "select-multiple":
if (obj.selectedIndex == -1){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
case "text":
case "textarea":
if (obj.value == "" || obj.value == null){
alertMsg += " - " + fieldDescription[i] + "\n";
}
break;
default:
}
if (obj.type == undefined){
var blnchecked = false;
for (var j = 0; j < obj.length; j++){
if (obj[j].checked){
blnchecked = true;
}
}
if (!blnchecked){
alertMsg += " - " + fieldDescription[i] + "\n";
}
}
}
}
if (alertMsg.length == l_Msg){
return true;
}else{
alert(alertMsg);
return false;
}
}
这是我用于下拉列表的代码:
<select name="country" id="country">
<option value="" disabled="disabled">Please select your country</option>
<option value="United Kingdom">United Kingdom</option>
<option value="United States">United States</option>
...
让用户选择一个国家/地区而不是让用户选择“请选择您的国家/地区”并且不返回任何内容,我缺少什么?
最佳答案
对于您的示例,此代码将始终结果为 true:
obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""
两者都将评估为 true。尝试将其更改为:
obj.selectedIndex == 0
关于javascript - 强制下拉问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821077/