从选择框中获取选定值无效

Getting a selected value from select box doesnt work

本文关键字:无效 获取 选择      更新时间:2023-09-26

我制作了一个函数,在点击时使用另一个选择框中的值填充一个选择盒,它对系统中的大多数选择框都很有效,但我现在很难处理这个问题lol:

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

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输出,也是WORKING

<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>

这不起作用。即使它在你的页面上有效,你帖子中的代码也无法工作:你的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和函数。例如,您肯定需要停止使用这么多字符串和查找。特别是相信字符串没有拼写错误会毁了你的一天(你有一个名为"专业3_"的输入和一个称为"专业3"的选择……这只是在找麻烦)