【问题标题】:Set selected option of Country and State to USA将国家和州的选定选项设置为美国
【发布时间】:2017-08-03 00:24:00
【问题描述】:

我正在注册一个国家和州的下拉列表。 我的问题是我不知道如何将默认国家/地区设置为 USA 和 USA 下的州。

我更改了 element.length 和 element.option 的值以及选定的索引,但它不起作用。

示例

JSFIDDLE

代码

function populateStates(countryElementId, stateElementId) {

    var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;

    var stateElement = document.getElementById(stateElementId);

    stateElement.length = 0; // Fixed by Julian Woods
    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++) {
        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);
    countryElement.length = 0;
    countryElement.options[0] = new Option('Select Country', '-1');
    countryElement.selectedIndex = 0;
    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);
        };
    }
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    http://jsfiddle.net/qw75h3vz/

    检查一下:

    function populateCountries(countryElementId, stateElementId) {
        // given the id of the <select> tag as function argument, it inserts <option> tags
        var countryElement = document.getElementById(countryElementId);
        countryElement.length = 0;
        countryElement.options[0] = new Option('Select Country', '-1');
        countryElement.selectedIndex = 0;
        for (var i = 0; i < country_arr.length; i++) {
            countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
             if(country_arr[i]=="USA") {
                countryElement.selectedIndex=countryElement.length-1;
                populateStates(countryElementId, stateElementId);
             }
        }
    

    在 for 循环中验证 if。

    【讨论】:

    • 我更新了我的答案。我错过了 if 行上的 1。我还包括了工作小提琴:jsfiddle.net/Lw82jgtd
    • 它工作先生,但我还需要显示状态的内容.. 我会试试你的代码
    猜你喜欢
    • 2014-08-04
    • 2014-10-27
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多