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

      

  • 相关阅读:
    debug和console.write()有什么区别
    数据源绑定DataGridViewComboBox
    关于SqlDataAdapter的Update()方法
    反思。。
    C语言光标移动
    关于湖南工业大学“蓝桥杯”预选赛
    Left digit
    突然想写个超级马里奥
    如何知道一个数有多大位数
    Hut 新生训练赛第二场 迟来的解题报告
  • 原文地址:https://www.cnblogs.com/f6056/p/11988518.html
Copyright © 2011-2022 走看看