【问题标题】:Getting a selected value from select box doesnt work从选择框中获取选定的值不起作用
【发布时间】:2013-02-06 16:42:00
【问题描述】:

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

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

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 html


【解决方案1】:

这不起作用。即使它在您的页面上运行,您帖子中的代码也无法运行:您的 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”的选择......这只是自找麻烦)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2019-07-30
    • 2011-03-13
    • 2015-01-27
    • 2015-11-27
    相关资源
    最近更新 更多