【问题标题】:Cant get dropdown selected value with javascript?无法使用 javascript 获取下拉选择值?
【发布时间】:2013-07-19 11:40:29
【问题描述】:

我的下拉列表(填充有objectDataSource):

<asp:DropDownList runat=server ID="ddlUserTypes" DataSourceID="odsUserTypes" AppendDataBoundItems=true DataTextField="UserType" DataValueField="Usertype">
<asp:ListItem Value="">-Please select one-</asp:ListItem>
</asp:DropDownList>

Javascript 函数获取下拉列表的选定值:

<script type="text/javascript" language="javascript">
    var notRegistered = false;
    var email = '';
    var userType = document.getElementById("ddlUserTypes");
    var pow = userType.options[userType.selectedIndex].value;
    function PreRegister() {debugger;
        if (notRegistered) {
            location.href = '/Register.aspx?pageid=<%= ConfigHelper.RegistrationPageId %>&Email=' + encodeURIComponent(email)+'&asd='+encodeURIComponent(pow);
            return false;
        }
        return true;
    }
</script>

但这不起作用pow 只是继续返回未定义?这可能是因为用户类型似乎没有得到任何分配给它的东西,因为它保持为空?有人知道为什么这段代码不起作用吗?

【问题讨论】:

  • ddlUserTypes 不是 clientId。
  • 什么意思?我是 javascript 新手
  • 在下面阅读我的答案。
  • 我尝试了你的建议,但 'userType' 仍然为 null 并且 'pow' 仍然未定义

标签: c# javascript


【解决方案1】:

正如 gdoron 提到的,ASP.Net 将使您的下拉列表的 HTML id 与您设置为 &lt;asp:DropDownList&gt; 的 ID 参数不同,这就是您的 JS 找不到它的原因。

最简单的方法是为下拉列表分配一个类,然后在 JS 中按类定位元素。

【讨论】:

  • 如何按班级定位?
  • document.getElementsByClassName,尽管您可能想考虑使用 jQuery,因为它使这种事情变得更加方便。
  • 尝试按类定位,但仍不确定
  • 你是如何在 DropDownList 中指定类的?
【解决方案2】:

使用它,我希望它有效。

var e = document.getElementById("ddlUserTypes");
var strUser = e.options[e.selectedIndex].value;

【讨论】:

    【解决方案3】:
    var userType = documentgetElemebyById('<%= ddlUserTypes.ClientID %>');
    

    You should read this

    【讨论】:

      【解决方案4】:
      <asp:DropDownList CssClass="ddlClass" ...>
      

      它会变成这样

      <select class="ddlClass" ...>
          <option value="value1">value1</option>
          <option selected="selected" value="value2">value2</option>
          ...
      </select>
      
      // use jQuery
      var selected = $('.ddlClass').val();
      
      // withour jQuery 
      // method1
      var selected1 = document.querySelector('.ddlClass option[selected="selected"]').value;
      // method2
      var selected2 = document.querySelector('.ddlClass option:checked').value;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-01
        • 1970-01-01
        相关资源
        最近更新 更多