我在注册工作,我有一个国家和州的下拉列表。 我的问题是我不知道如何将默认国家设置为美国和美国的州。
我更改了element.length和element.option的值以及所选索引,但它不起作用。
样品
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);
};
}
}
答案 0 :(得分:1)
检查一下:
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。