zoukankan      html  css  js  c++  java
  • 获取下拉框的文本值和value值

    http://www.cnblogs.com/djgs/p/3691979.html?utm_source=tuicool&utm_medium=referral

    现在有一个Id为AreaId的下拉框,要获取它当前选择项的文本和值有以下方法:

    复制代码
    <span class="red">* </span>
    地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区:
    <span>
          <select id="AreaId" name="AreaId" size="1" class="sel">
               <option>-请选择地区-</option>
               <option value="1">北京</option>
               <option value="2">上海</option>
               <option value="3">深圳</option>
           </select>
    </span>            
    复制代码

    方法一:使用JavaScript原生态的方法.

      1.获取值:    

    复制代码
    document.getElementById("AreaId").value;//有效,能得到正确的值.

    var index=document.getElementById("AreaId").selectedIndex;//获取当前选择项的索引.
    document.getElementById("AreaId").options[index].value;//获取当前选择项的值.

     var obj=document.getElementById("AreaId");

            for(i=0;i<obj.length;i++) {//下拉框的长度就是它的选项数.

               if(obj[i].selected==true) {

                var text=obj[i].value;//获取当前选择项的值.

          }

        }

    复制代码

      2.获取文本:

    复制代码
    var index=document.getElementById("AreaId").selectedIndex;//获取当前选择项的索引.
    document.getElementById("AreaId").options[index].text;//获取当前选择项的文本.

    document.getElementById("AreaId").options[index].innerHTML;//获取当前选择项的文本.

     var obj=document.getElementById("AreaId");

            for(i=0;i<obj.length;i++) {//下拉框的长度就是它的选项数.

               if(obj[i].selected==true) {

                var text=obj[i].text;//获取当前选择项的文本.

          }

        }

    document.getElementById("AreaId").text;//注意,这句代码无效,得到的结果为undefined.
    复制代码

    方法二:使用JQuery方法(前提是已经加载了jquery库).

      1.获取值:

    $("#AreaId").val();//获取当前选择项的值.

    var options=$("#AreaId option:selected");//获取当前选择项.
    options.val();//获取当前选择项的值.

      2.获取文本:

    var options=$("#AreaId option:selected");//获取当前选择项.
    options.text();//获取当前选择项的文本.

    options.innerHTML();//获取当前选择项的文本.

    $("#AreaId").text;//注意,这句代码无效,得到的结果为undefined.

    其他属性:  

    复制代码
    innerText:

    var index=document.getElementById("AreaId").selectedIndex;//获取当前选择项的索引.
    document.getElementById("AreaId").options[index].innerText;//获取当前选择项的文本,IE支持,Firefox不支持.

    document.getElementById("AreaId").innerHTML;//获取当前下拉框所有的元素,包括Html代码.注意大小写.
    document.getElementById("AreaId").textContent;//获取当前下拉框中所有的选择项文本,不包括Html代码.
    复制代码
  • 相关阅读:
    HDU5418.Victor and World(状压DP)
    POJ2686 Traveling by Stagecoach(状压DP)
    POJ3254Corn Fields(状压DP)
    HDU5407.CRB and Candies(数论)
    CodeForces 352D. Jeff and Furik
    CodeForces 352C. Jeff and Rounding(贪心)
    LightOj 1282 Leading and Trailing
    Ural 1057. Amount of Degrees(数位DP)
    HDU 2089 不要62 (数位DP)
    HDU5366 The mook jong (DP)
  • 原文地址:https://www.cnblogs.com/LuoXiaoTing604404828/p/5124283.html
Copyright © 2011-2022 走看看