首页 新闻 赞助 找找看

javascrip 获取 DorpDownList 选中值

0
[已解决问题] 解决于 2009-03-24 14:10

运行后 总是得出 undefind

我也觉得这样写有什么问题。请高人指点

如果一定要在运行是给它添加事件

应如何改?

以下是代码段:

aspx:

------------------------------------------------------------

<html>

<head>

<script language="javascript" type="text/javascript" src="Script/Default.js"></script>

</head>

<body>

<form id="frim1" runat="sever" action="">

<asp:DropDownList ID="ddl" runat="sever"></DropDownList>

</form>

<body>

-----------------------------------------------

cs:

--------------------------------------------------------------

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
             ddl.Attributes.Add("onChange", "javascript:TextBoxEnable("ddl")");
        }
    }

-------------------------------------

js

-----------------------------------------

function TextBoxEnable(ddlName)
{
    ddl=document.getElementById(ddlName);
    index =ddl.seletedIndex;
    alert(index);
}

湖的主页 | 初学一级 | 园豆:0
提问于:2009-03-19 17:46
< >
分享
最佳答案
0

写了个完整的代码给你贴在下面

这是html代码<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  <asp:DropDownList ID="DropDownList1" runat="server" >
   <asp:ListItem Value="1">我是1个一</asp:ListItem>
   <asp:ListItem Value="2">我是2个二</asp:ListItem>
  </asp:DropDownList>
   
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
 function sel(oid) {
  oid = document.getElementById(oid);
  var index = oid.options[oid.selectedIndex].value;
  alert(index);
 }
</script>

这是c#代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
  if (!IsPostBack) this.DropDownList1.Attributes.Add("OnChange", "return  sel('DropDownList1')");
    }
}
 

西越泽 | 专家六级 |园豆:10775 | 2009-03-21 01:06
其他回答(4)
0

  ddl=document.getElementById(ddlName);
    index =ddl.value;
    ;

重典 | 园豆:2442 (老鸟四级) | 2009-03-19 19:46
0

楼上是的正解,不过只能得到选中的值,不能得到序号。

如果你想理解dropdownlist你可以看一下HTML 标记中select标签有哪些属性。

LeoLWang | 园豆:205 (菜鸟二级) | 2009-03-19 22:07
0

查看生成的html源码,看看ddl生成的id是什么。在asp.net 1.1里面是ddl,但在2.0以后的生成的ID往往会有些前缀的

Waitd Ding | 园豆:235 (菜鸟二级) | 2009-03-19 22:22
0

楼主,改这三个位置的代码。
from:ddl.Attributes.Add("onChange", "TextBoxEnable("ddl")");
to:ddl.Attributes.Add("onChange", "TextBoxEnable(this)");

from:function TextBoxEnable(ddlName)
to:function TextBoxEnable(el)

from:ddl=document.getElementById(ddlName);
index =ddl.seletedIndex;

to:index=el.selectedIndex;

I,Robot | 园豆:9783 (大侠五级) | 2009-03-20 09:55
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册