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 + "个选项。");
          }
        }
    

      

  • 相关阅读:
    【Maven】项目打包-war包-Jar包[IDEA将项目打成war包]
    intellij idea 配置web 项目
    centos7启动iptables时报Job for iptables.service failed because the control process exited with error cod
    shell-运算符
    shell-流程控制
    shell-流程控制
    shell-变量,字符串,数组,注释,参数传递
    shell-变量,字符串,数组,注释,参数传递
    json解析
    json解析
  • 原文地址:https://www.cnblogs.com/f6056/p/11988518.html
Copyright © 2011-2022 走看看