首页 > Web开发 > 详细

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

时间:2019-12-05 13:19:16      阅读:77      评论:0      收藏:0      [点我收藏+]

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

  

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

原文:https://www.cnblogs.com/f6056/p/11988518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!