2017-03-13 20 views
0

私は国と州のドロップダウンリストを持つ登録作業中です。 私の問題は、デフォルトの国を米国と米国の州に設定する方法がわかりません。国と州の選択されたオプションを米国に設定します

element.lengthとelement.optionの値と選択されたインデックスは変更されますが、機能しません。

SAMPLE

JSFIDDLE

CODE

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

答えて

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ループ内にあるかどうかを確認します。

+0

ありがとうございました。でも、うまくいきません。 –

+0

私の回答が更新されました。私はifラインで1を見逃しました。私はまた働いています:http://jsfiddle.net/Lw82jgtd/ –

+0

それは、私は国家の内容も表示する必要がありますが、私は働いています。病気あなたのコードを試して –

関連する問題