0

我创建了一个函数,在单击时使用另一个选择框的值填充一个选择框,它对于系统中的大多数选择框都工作得很好,但我现在正在努力解决这个问题,哈哈:

用于测试所选值并在发现时发出警报的功能:

function updateSelectBox(parent, child){
    for(i = 0; i < document.getElementById(parent).length; i++){
        if(document.getElementById(parent).options[i].selected){
            alert(document.getElementById(parent).options[i].value);
    }
}

选择此选项时不会发出警报:

<input type="hidden" name="data[Series][3][Profession][Profession]" value="" id="Professions3_">
<select name="data[Series][3][Profession][Profession][]" multiple="multiple" id="Professions3" onchange="updateSelectBox("Professions3", "Specialisms3");">
<option value="24">Scientist</option>

选择时会发出警报:

<input type="hidden" name="data[Series][4][Profession][Profession]" value="" id="Professions4_">
<select name="data[Series][4][Profession][Profession][]" multiple="multiple" id="Professions4" onchange="updateSelectBox("Professions4", "Specialisms4");">
<option value="24">Scientist</option>

这是来自不同选择框的完整 html 输出,也可以工作

<div class="input select"><label for="Zones">Zones</label><input type="hidden" name="data[Series][0][Zone][Zone]" value="" id="Zones_">
<select name="data[Series][0][Zone][Zone][]" multiple="multiple" id="Zones" onchange="updateSelectBox(&quot;Zones&quot;, &quot;Countries&quot;);">
<option value="4">Europe</option>
</select>
</div>
4

1 回答 1

0

这行不通。即使它在您的页面上运行,您帖子中的代码也无法运行:您的 JavaScript 缺少右括号,您在双引号内使用带有双引号的 HTLM,没有人能够运行它。所以让我们退后一步,把它改写成肯定会起作用的东西:

HTML

<select onchange="updateSelectBox(this);">
  <option value="0">Scientist 1</option>
  <option value="12">Scientist 2</option>
  <option value="24">Scientist 3</option>
</select>

JS

function updateSelectBox(selectBox) {
  var sid = selectBox.selectedIndex;
  var selectedOption = selectBox.children[sid];
  console.log(selectedOption);
}

现在我们至少有了一些我们知道可以使用的东西,使用最少的代码,我们可以重新构建。我建议使用它来构建您现在拥有的 HTML 和功能。例如,您肯定需要停止使用如此多的字符串和查找。特别是相信没有错别字的字符串会毁了你的一天(你有一个名为'Professions3_'的输入和一个名为'Professions3'的选择......这只是自找麻烦)

于 2013-02-06T17:25:11.047 回答