2016-01-06 74 views
0

我認爲我的選擇狀態下拉框會自動顯示「選擇狀態」但是,這並沒有像我預料的那樣工作。下拉框爲空,直到我選擇一個國家,然後纔將狀態下拉框顯示「選擇的狀態。我如何設置我的狀態下拉框‘默認選擇狀態’?如何設置下拉選擇的默認值

function populateStates(countryElementId, stateElementId) { 
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex; 
var stateElement = document.getElementById(stateElementId); 

stateElement.length = 0; // 
stateElement.options[0] = new Option('Select State', ''); 
stateElement.selectedIndex = 0; 

var state_arr = s_a[selectedCountryIndex].split("|"); 

for (var i = 0; i < state_arr.length; i++) { 
    if (state_arr[i] != "") { 
     stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]); 
    } 
    } 
} 

function populateCountries(countryElementId, stateElementId) { 
// given the id of the <select> tag as function argument, it inserts <option> tags 
var countryElement = document.getElementById(countryElementId); 
jQuery("#" + countryElementId + " option").remove(); 
jQuery("#" + countryElementId).append("<option value=\"\">USA</option>"); 
for (var i = 0; i < country_arr.length; i++) { 
    countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]); 
} 

// Assigned all countries. Now assign event listener for the states. 
if (stateElementId) { 
    countryElement.onchange = function() { 
     populateStates(countryElementId, stateElementId); 
     jQuery("#" + stateElementId + " option:eq(0)").attr("selected", "selected"); 
     jQuery("#" + stateElementId).val("").change(); 
     if (jQuery("#" + countryElementId).val() == "USA") { 
      jQuery("#Zip_Postal_Code__c").attr("maxlength", "5"); 
     } else if (jQuery("#" + countryElementId).val() == "Canada") { 
      jQuery("#Zip_Postal_Code__c").attr("maxlength", "6"); 
     } else { 
      jQuery("#Zip_Postal_Code__c").removeAttr("maxlength"); 
     } 
    }; 
} 

}

回答

1

你可以使用默認的狀態下拉HTML只包含一個選項:選擇國家例如,在HTML

<select id="state_select"> 
    <option value="">Select State</option> 
</select> 
1

爲了防止選擇了第一個選項:

<select> 
 
     <option value="" disabled selected hidden>Select State</option> 
 
     <option value="USA">USA</option> 
 
     <option value="Canada">Canada</option> 
 
    </select>