首页 > javascript > javascript操作dropdownlist值测试

javascript操作dropdownlist值测试

2009年10月14日 云飞扬 发表评论 阅读评论

问题描述:根据改变dropdownlist项取得相应的text和value值

在javascript中ddl.selectedIndex无法再另外单独分离出来,类似的问题http://space.cnblogs.com/question/4638/
错误的写法如下:
// var ddl = document.getElementById("ddlGuo");
           // alert(ddl);
//            var index = ddl.selectedIndex;
//            alert(index);
//            var a = ddl.options[index].value;
//            var b = ddl.options[index].text;

//            alert(a);
 //  alert(b);

如果改为下面这样就正确了
var ddl = document.getElementById("ddlGuo");
            var a = ddl.options[ddl.selectedIndex].value;
            var b = ddl.options[ddl.selectedIndex].text;

完整的测试代码

<%@ 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>
    <script language="javascript" type="text/javascript">
        function onalert() {

           // var ddl = document.getElementById("ddlGuo");
           // alert(ddl);
//            var index = ddl.selectedIndex;
//            alert(index);
//            var a = ddl.options[index].value;
//            var b = ddl.options[index].text;
//            alert(a);
 //  alert(b);
          
            var ddl = document.getElementById("ddlGuo");
            var a = ddl.options[ddl.selectedIndex].value;
            var b = ddl.options[ddl.selectedIndex].text;

            //var a = document.getElementById("ddlGuo").options[document.getElementById("ddlGuo").selectedIndex].value;
            // var b = document.getElementById("ddlGuo").options[document.getElementById("ddlGuo").selectedIndex].text;
            document.getElementById("txtval").value = a;
            document.getElementById("txttext").value = b;
            alert(a+b);
        }
      
    </script>
</head>
<body  >
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlGuo" runat="server"  onchange="onalert();" >
            <asp:ListItem Selected="True" Value="1">C国</asp:ListItem>
            <asp:ListItem Value="2">D国</asp:ListItem>
            <asp:ListItem Value="3">E国</asp:ListItem>
      
        </asp:DropDownList>
        <asp:TextBox ID="txtval" runat="server"></asp:TextBox>
        <asp:TextBox ID="txttext" runat="server"></asp:TextBox>
   
    </div>
    </form>
</body>
</html>

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/368

分类: javascript 标签:
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.