代码之家  ›  专栏  ›  技术社区  ›  Eyeball

Javascript复选框选择顺序

  •  3
  • Eyeball  · 技术社区  · 14 年前

    如何检测复选框的选中顺序?我在表单上有一个复选框列表,我需要让用户选择他们的第一个和第二个选择(但不需要更多)。所以,考虑到这一点:

    <input name="checkbox1" type="checkbox" value="a1"> Option 1
    <input name="checkbox1" type="checkbox" value="a2"> Option 2
    <input name="checkbox1" type="checkbox" value="a3"> Option 3
    <input name="checkbox1" type="checkbox" value="a4"> Option 4
    

    如果有人选择了选项2,然后是选项3,我想有一些指标,选项2是第一个选择,选项3是第二个选择。有什么想法吗?

    提前谢谢。

    更新:

    这些都是非常有用的建议,谢谢。当我测试这些例子时,它让我对如何解决这个问题有了更好的认识——但我还是有点卡住了(我是一个JS新手)。我要做的是在复选框被选中或取消选中时更改这些标签,以指示哪个是第一个或第二个选择:

    <label id="lblA1"></label><input name="checkbox1" type="checkbox" value="a1"> Option 1
    <label id="lblA2"></label><input name="checkbox1" type="checkbox" value="a2"> Option 2
    <label id="lblA3"></label><input name="checkbox1" type="checkbox" value="a3"> Option 3
    <label id="lblA4"></label><input name="checkbox1" type="checkbox" value="a4"> Option 4
    

    因此,如果有人单击选项2,那么选项3,lblA2将显示“First”,lblA3将显示“Second”。如果有人在选项3仍处于选中状态时取消选中选项2,则lblA3变为“第一个”。希望这有意义?

    谢谢!

    6 回复  |  直到 14 年前
        1
  •  3
  •   Musa Hafalir    14 年前

    如果您使用的是jQuery。下面的代码是做什么,你已经解释和测试。 我使用了全局变量。

    <input name="checkbox1" type="checkbox" value="a1" /> Option 1
    <input name="checkbox1" type="checkbox" value="a2" /> Option 2
    <input name="checkbox1" type="checkbox" value="a3" /> Option 3
    <input name="checkbox1" type="checkbox" value="a4" /> Option 4
    <input type="button" value="do" id="btn" />
    

    如下所示,它还处理用户取消选中选项的情况。

    $(document).ready(function () {
        var first = "";
        var second = "";
        $('input[name="checkbox1"]').change(function () {
            if ($(this).attr('checked')) {
                if (first == "") {
                    first = $(this).attr('value');
                }
                else if (second == "") {
                    second = $(this).attr('value');
                }
            }
            else {
                if (second == $(this).attr('value')) {
                    second = "";
                }
                else if (first == $(this).attr('value')) {
                    first = second;
                    second = "";
                }
            }
        });
        $('#btn').click(function () {
            alert(first);
            alert(second);
        });
    });
    

    我希望这会有帮助。

    完整的HTML:

    <label id="lblA1"></label>
    <input name="checkbox1" type="checkbox" value="a1" /> Option 1
    <label id="lblA2"></label>
    <input name="checkbox1" type="checkbox" value="a2" /> Option 2
    <label id="lblA3"></label>
    <input name="checkbox1" type="checkbox" value="a3" /> Option 3
    <label id="lblA4"></label>
    <input name="checkbox1" type="checkbox" value="a4" /> Option 4
    

    完整的Javascript:

    $(document).ready(function () {
        var array = [];
        $('input[name="checkbox1"]').click(function () {
            if ($(this).attr('checked')) {
                // Add the new element if checked:
                array.push($(this).attr('value'));
            }
            else {
                // Remove the element if unchecked:
                for (var i = 0; i < array.length; i++) {
                    if (array[i] == $(this).attr('value')) {
                        array.splice(i, 1);
                    }
                }
            }
            // Clear all labels:
            $("label").each(function (i, elem) {
                $(elem).html("");
            });
            // Check the array and update labels.
            for (var i = 0; i < array.length; i++) {
                if (i == 0) {
                    $("#lbl" + array[i].toUpperCase()).html("first");
                }
                if (i == 1) {
                    $("#lbl" + array[i].toUpperCase()).html("second");
                }
            }
        });
    });
    
        2
  •  0
  •   Vinay B R    14 年前

    第一个和第二个javascript变量。每当复选框被选中时,检查first是否为null如果是,则为其分配复选框id,如果first不为null则设置second。

        3
  •  0
  •   Felix Kling    14 年前

    您可以有一个更改侦听器和一个隐藏字段。每次用户选中复选框时,您都会添加值。像这样(假设 #parent 是框的父元素):

    $('#parent').delegate('input[type=checkbox]', 'change', function() {
        if($(this).is(':checked')) {
            $('#hidden').val($('#hidden').val() + " " + $(this).val())
        }
    });
    

    隐藏字段的值将类似于 a2 a3 a1 ...

    这是如果您想在服务器端处理信息的话。然后可以在服务器端拆分字符串并检查它。当然,您必须处理选择的删除和添加。


    如果只想处理客户端上的值,可以将其添加到数组中:

    var selected = [];
    $('#parent').delegate('input[type=checkbox]', 'change', function() {
        if($(this).is(':checked')) {
            selected.push($(this).val());
        }
    });
    
        4
  •  0
  •   Alpesh    14 年前

    试试看-

    $(document).ready(function(){
    var checked_no = 0;
    $('input[name="checkbox1"]').change(function(){
    alert($('input[name="checkbox1"]').filter(':checked').length);
    checked_no = $('input[name="checkbox1"]').filter(':checked').length;
    // checked_no acts as a counter for no of checkboxes checked.
    });
    });
    
        5
  •  0
  •   Victor Ionescu prashant thakre    14 年前

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
        <script type = "text/javascript">
            var checkboxClicks =  new Array(2);
            function updateClickOrder(checkbox) {
                if (checkbox.checked) {
                    if (checkboxClicks[0] ==null) {
                        checkboxClicks[0]  = checkbox.value;
                    } else if (checkboxClicks[1] ==null) {
                        checkboxClicks[1]  = checkbox.value;
                    }
                }
                document.forms[0].clickOrder.value = checkboxClicks[0] + ", " + checkboxClicks[1];
                alert(document.forms[0].clickOrder.value);
                //alert("Clicked " + checkbox.value);
            }
    
        </script>
    </head>
    <body>
    <form name="testCheckboxClickOrder">
        <input name="checkbox1" type="checkbox" value="a1" onchange="updateClickOrder(this);"> Option 1
        <input name="checkbox1" type="checkbox" value="a2" onchange="updateClickOrder(this);"> Option 2
        <input name="checkbox1" type="checkbox" value="a3" onchange="updateClickOrder(this);"> Option 3
        <input name="checkbox1" type="checkbox" value="a4" onchange="updateClickOrder(this);"> Option 4
        <input type="hidden" name="clickOrder"/>
    </form>
    </body>
    </html>
    
        6
  •  0
  •   BrunoLM    14 年前

    <input type="checkbox" value="v1" />
    <input type="checkbox" value="v2" />
    <input type="checkbox" value="v3" />
    <input type="checkbox" value="v4" />
    
    <textarea id="result"></textarea>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script>
        var userInput = [];
        var c = 0;
    
        $("input[type=checkbox]").click(function()
        {
            if ($(this).attr("checked"))
            {
                userInput[c] = $(this).val();
                ++c;
            }
            else
            {
                var i = parseInt(userInput.join().indexOf($(this).val())) - 2;
                userInput.splice(i, 1);
            }
        });
    
    
        $("textarea").click(function()
        {
            $(this).val("");
            for (var i in userInput)
            {
                $(this).val($(this).val() + " " + userInput[i]);
            }
        });
    </script>
    
        7
  •  0
  •   Rahul mukeri    5 年前

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
    <input name="checkbox1" type="checkbox" id="myCheck" value=" Option 1" onclick="myFunction('Option 1')" /> Option 1
    <input name="checkbox1" type="checkbox" id="myCheck2" value=" Option 2" onclick="myFunction2('Option 2')" /> Option 2
    <input name="checkbox1" type="checkbox" id="myCheck3" value=" Option 3" onclick="myFunction3('Option 3')" /> Option 3
    <input name="checkbox1" type="checkbox" id="myCheck4" value=" Option 4" onclick="myFunction4('Option 4')" /> Option 4
    <p id="getValues"></p>
    </body>
    <script>
    var array = [];
    function removeA(arr) {
        var what, a = arguments, L = a.length, ax;
        while (L > 1 && arr.length) {
            what = a[--L];
            while ((ax= arr.indexOf(what)) !== -1) {
                arr.splice(ax, 1);
            }
        }
        return arr;
    }
    
    function myFunction(text) {
      // Get the checkbox
      var checkBox = document.getElementById("myCheck");
      // Get the output text
      // If the checkbox is checked, display the output text
      if (checkBox.checked == true)
      {
        array.push(text);
      }
      else
      {
      	removeA(array, text);
      }
      getValues();
    }
    function myFunction2(text) {
      // Get the checkbox
      var checkBox = document.getElementById("myCheck2");
      // Get the output text
      // If the checkbox is checked, display the output text
      if (checkBox.checked == true)
      {
        array.push(text);
      }
      else
      {
      	removeA(array, text);
      }
      getValues();
    }
    function myFunction3(text) {
      // Get the checkbox
      var checkBox = document.getElementById("myCheck3");
      // Get the output text
      // If the checkbox is checked, display the output text
      if (checkBox.checked == true)
      {
        array.push(text);
      }
      else
      {
      	removeA(array, text);
      }
      getValues();
    }
    function myFunction4(text) {
      // Get the checkbox
      var checkBox = document.getElementById("myCheck4");
      // Get the output text
      // If the checkbox is checked, display the output text
      if (checkBox.checked == true)
      {
        array.push(text);
      }
      else
      {
      	removeA(array, text);
      }
      getValues();
    }
    
    function getValues()
    {
    	$("#getValues").html(array.join("<br>"));
    }
    </script>
    </html>