繁体   English   中英

如何设置下拉菜单的默认值

[英]How can I set the default value for a dropdown selection

我以为我的选择状态下拉框将自动显示“选择状态”,但是,这没有达到我的预期。 下拉框为空,直到选择一个国家,然后状态下拉框才会显示“选择州”。默认情况下,如何将状态下拉框设置为“选择州”?

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

}

您可以只使用默认状态下拉html只包含一个选项:选择“状态”。 例如在HTML

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

为了防止选择第一个选项:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM