实现选择集动态选项问题

时间:2016-09-30 09:22:31

标签: javascript html materialize

我有两个依赖的下拉菜单(物化选择)国家和州。在选择国家/地区我正在使用javascript获得尊重状态,我正在添加状态选择的选项,但它在状态下拉列表中显示为空...但是当我提醒,价值正确。任何人都可以帮我解决这个问题吗?

编辑: 删除显示后使用inspect:无选择我得到如下...实际html选择下拉列表正确填充但实现选择不显示或填充为什么? See image here
HTML代码:

 <select name="country" id="country" onchange="setStates();" style="width:100px; font-weight:bold;" >
     <option value="">Select</option>
      /* Country  options here */
    </select>
 <select name="state" id="state" style="width:100px; font-weight:bold;" >
    </select>

Javascript代码:

function setStates() {

  cntrySel = document.getElementById('country');
  stateList = states[cntrySel.value];

  changeSelect('state', stateList, stateList);
}

function changeSelect(fieldID, newOptions, newValues) {
  selectField = document.getElementById(fieldID);
  selectField.options.length = 0;

  for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
  }

}

2 个答案:

答案 0 :(得分:1)

你必须重新初始化物化选择,试试这个:

function setStates() {

  cntrySel = document.getElementById('country');
  stateList = states[cntrySel.value];

  changeSelect('state', stateList, stateList);
}

function changeSelect(fieldID, newOptions, newValues) {
  selectField = document.getElementById(fieldID);
  selectField.options.length = 0;

  for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
  }
  // Materialize old version
  $('#'+fieldID).material_select();
  // Materialize new version
  $('#'+fieldID).select();

}

答案 1 :(得分:0)

这应该有效:

function setStates() {

  cntrySel = document.getElementById('country');
  stateList = states[cntrySel.value];

  changeSelect('state', stateList, stateList);
}

function changeSelect(fieldID, newOptions, newValues) {
  selectField = document.getElementById(fieldID);
  selectField.options.length = 0;

  for (i=0; i<newOptions.length; i++) {
    selectField.innerHTML= "<option value=\"" + newValue[i] + "\">" + newOption[i] + "</option>"
  }

}