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

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号