zoukankan      html  css  js  c++  java
  • JS如何判断表单中用户选择哪个哪个选项?

    JS如何判断表单中用户选择哪个哪个选项?

    HTML代码:

    <form name="form1" onsubmit="return foo();">
    
        A<input type="radio" name="radioGroup" value="a" />
    
        B<input type="radio" name="radioGroup" value="b" />
    
        C<input type="radio" name="radioGroup"   />
    
        D<input type="radio" name="radioGroup" />
    
        E<input type="radio" name="radioGroup" />
    
        F<input type="radio" name="radioGroup" />
    
        <input type="submit" />
    
      </form>

    方法一:元素集合转换为数组实例,根据当前元素在数组中对应的索引位置判断元素。

        var aInput = document.getElementsByTagName("input");
        var arry = [];
        var nowIndex = null;
        for (var i = 0; i < aInput.length-1; i++) {
          arry[i] = aInput[i];
          aInput[i].onclick = function () {
            nowIndex = arry.indexOf(this);
            console.log("点击了第" + nowIndex + "个选项。");
          }
        }
        function foo() {
          alert(nowIndex+1);
        }

    方法二:通过input元素的value值来判断点击的元素索引,缺陷是此方法不如第一种方法灵活,移植性较差。

        function foo() {
          alert(nowIndex+1)
        }
        var aInput = document.getElementsByTagName("input");
        var arry = [];
        var nowIndex = null;
        for (var i = 0; i < aInput.length-1; i++) {
    
          aInput[i].onclick = function () {
    
            var optValue = this["value"];
            switch (optValue) {
              case "a":
                nowIndex = 0;
                break;
              case "b":
                nowIndex = 1;
                break;
              case "c":
                nowIndex = 2;
                break;
              case "d":
                nowIndex = 3;
                break;
              case "e":
                nowIndex = 4;
                break;
              case "f":
                nowIndex = 5;
                break;
              default:
                nowIndex = null;
                ;
    
            }
            console.log("点击了第" + nowIndex + "个选项。");
          }
        }
    

      

  • 相关阅读:
    use imagination
    tar
    简单抓取安居客房产数据,并保存到Oracle数据库
    svn的安装(整合apache、ldap)包括错误解决post commit FS processing had error
    SVN安装中遇到的问题
    Linux环境源码编译安装SVN
    [转]SVN安装问题The Apache Portable Runtime (APR) library cannot be found
    深入浅出数据分析-脑图
    Python3.5在Windows 7下连接ORACLE数据库
    Python3.5之TuShare
  • 原文地址:https://www.cnblogs.com/f6056/p/11988518.html
Copyright © 2011-2022 走看看