我有一個表單有幾個必填字段,除了下拉菜單外,其他所有工作都是如此。強制性下拉問題
我正在使用此代碼來檢查的字段:
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>
...
我缺少的是使用戶選擇一個國家,而不是讓他們離開「請選擇你的國家」,它什麼都不返回?
而不是重新發明輪子,我建議你使用像jQuery一樣的JavaScript庫。您將獲得處理跨瀏覽器差異的可靠,穩健的代碼。 – RedFilter 2012-01-11 14:43:38
@RedFilter:更不用說整個代碼塊可以減少到10 LLOC。 – 2012-01-11 14:49:11