开发者

Javascript checkbox selection order

How would I go about detecting the order in which checkboxes are checked? I have a list of checkboxes on a form, and I need to have users select their first and second choices (but no more). So, given this:

<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

If someone selects option 2, then option 3, I'd like to have some indicator that option 2 was the first choice, and option 3 was the second choice. Any ideas?

Thanks in advance.

Update:

These are extremely helpful suggestions, thank you. As I test these examples, it's giving me a better idea of how to approach the problem - but I'm still a bit stuck (I'm a JS novice). What I want to do is have these labels change as the checkboxes are checked or unchecked, to indicate which is the first or second selection:

<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

So if someone clicks Option 2, then Option 3, lblA2 will display "First", and lblA3 will display "Second". If someone unchecks Option 2 while Option 3 is still checked, lblA3 becomes "First". Hopefully this makes sense?

Thanks!


If you are using jQuery. Below code is does what you have explained and it is tested. I have used global variables.

<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" />

As shown below, it also handles the situation that user unchecks a choice.

$(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);
    });
});

I hope that it will be helpful.

UPDATE [IMPORTANT]:

I have noticed that my previous code was incomplete, for example, if you check a1, then a2, then a3, then uncheck a2; my code was not recognising a3 as second. Here is the complete solution of your updated problem. I used array this time.

The complete 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

The complete 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");
            }
        }
    });
});


have 2 javascript variables first and second. whenever a checkbox is checked check if first is null if so assign the checkbox id to it, if first is not null set second.


You could have a change listener and a hidden field. Every time the user selects a checkbox, you add the value. Like so (assuming #parent is the parent element of the boxes):

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

The value of the hidden field would then be something like a2 a3 a1...

This is if you want to process the information at the server side. You can then split the string at the server side and examine it. Of course you have to handle removal and adding of selections.


If you just want to process the values on the client, you can add it to an array:

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


Try -

$(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.
});
});


Here you have it, if you want something more sophisticated (e.g. to test when an option is unclicked) you have to do some extra work. Just test this html in your browser:

<!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>


This is going to save the order in an array. If you deselect the position is removed. The script will attempt to find the element by its value and remove. If you select again the value is added.

<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>


<!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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜