在下拉列表中检索所选值,该下拉列表由vbscript使用Javascript填充,没有jquery可用

Retrieve a selected value in a drop down list that is populated by vbscript using Javascript with no jquery available

本文关键字:下拉列表 Javascript 使用 填充 没有 可用 jquery vbscript 检索      更新时间:2023-09-26

我正在尝试使用onclick事件检索下拉列表中选择的选项。当使用document.getElementbyID对值进行硬编码时,这很容易。需求已经改变,DDL是通过对服务器的vbscript调用来填充的。现在getElement不起作用,因为它正在根据我的调试器回调一个null值。以下是目前的代码:

<td id="td1" width="300" style="border: 0px solid #000000; border-collapse:collapse;"><span class="smalltextblk"><span class="text">
            Division</span>
            <span id="spnBusiness" name="spnBusiness"></span>
            </td>
            <td class="smalltextblk">
<td id="td2" width="150" style="border: 0px solid #000000; border-collapse:collapse;"><span class="smalltextblk"><span class="text">
            Year:
            <select name="YEAR" id="YEAR">
            <%=populateYearDropdown %>
            </select>          
            </td>
<td id="tdType" width="200" style="border: 0px solid #000000; border-collapse:collapse;"><span class="smalltextblk"><span class="text">
            Select Report Type:
            <select id="selType" name="selType">
            <option value="overview">Overview</option>
            <option value="withheld">Withheld</option>
      </select>
      <td>
        <button onclick="buttonFunction()">Generate</button>
      </td>

function buttonFunction() {
    var businessUnit = document.getElementById("spnBusiness");
    var yearSelection = document.getElementById("YEAR");
    var typeSelection = document.getElementById("selType");
    alert(businessUnit);
    alert(yearSelection);
    alert(typeSelection);
    }

警报显示我在点击generate后正在检索正确的值。

枚举<select>元素的<option>元素并检查其selected属性。

未测试的JavaScript片段:

var sel = document.getElementById('selType');
for (var i = 0; i < sel.options.length; i++) {
  if ( sel.options[i].selected ) {
    alert(sel.options[i].value);
  }
}