views:

129

answers:

7

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!

A: 

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.

Vinay B R
A: 

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.
});
});
Alpesh
A: 

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());
    }
});
Felix Kling
+1  A: 

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");
            }
        }
    });
});
Musa Hafalır
This put me onto the right track, thanks.
Ethan
I have updated my solution, as I mentioned, the first solution was incomplete. Please check the updated solution. Thanks.
Musa Hafalır
@Musa, but in the case "[a user checks] a1, then a2, then a3, then un-check a2", should the un-checking be considered a second (deliberate) action on a2, (to give the order: a1, a2, a3, a2) *or* the removal of an action (to give the order: a1, a3)? This idea seems a fun way to implement a non-captcha human verification.
David Thomas
A: 

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"&gt;
<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>
Victor Ionescu
A: 

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"&gt;&lt;/script&gt;
<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>
BrunoLM
A: 

I have a couple of questions if you dont mind, say I want eight selections, do I need to update this portion of the code

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

I have 20 check boxes, but I would like to limit to eight

is that possible?

James