I’m trying to get checked checkboxes in an array but I want them to be ordered in the order they are selected.
For example, I have 3 checkboxes—
<label for="check-1">check 1</label>
<input type="checkbox" id="check-1" value="1" name="mycheck[]">
<label for="check-2">check 2</label>
<input type="checkbox" id="check-2" value="2" name="mycheck[]">
<label for="check-3">check 3</label>
<input type="checkbox" id="check-3" value="3" name="mycheck[]">
—and I selected Check 2 then Check 3 then Check 1.
I want result to be in array like this (‘2′,’3′,’1’)
I use this function but it’s not get them to order
var list = new Array();
$('input[name="mycheck"]:checked').each(function() {
list.push([$(this).val()]);
});
console.log(list);
6
Answers
You can use this way
Hope it will be work 🙂
Be careful about state in general: User interaction is only one way to change state, and often there are more kinds of interaction possible than you can imagine.
Things often overlooked are state being set programmatically, for example via a “check all” checkbox, and keyboard interaction.
So in general it is better to listen on
change
than onclick
, and to work with the actual state when creating the final list. To symbolise that I created a button.Also, you’d need to take into account that users can uncheck and check again.
The approach here is to track the order in which each checkbox was checked, and then finally sort the actually checked checkboxes by their position in that kind of log.
This is using Array’s sort method and using the log of check events to compare which checkbox should come first.
lastIndexOf
is used because the last time the box got checked counts.You could also remove checkboxes from the log once they get unchecked, then
lastIndex()
would suffice.Should there be one box checked that did not trigger a
change
event,lastIndexOf()
would return -1 and that value would be first in the list.Added class
.chx
to each checkbox since it’s the easiest way to access a group of tags — I can’t think of a reason why you shouldn’t. Basically you need to use an event handler to pickup values that are derived from the user interacting with the checkboxes.Details are commented in example
This answer assumes values are unique.
When checked, push the value to an array.
When unchecked, remove it from the array.
Using jQuery
on()
method to capture the Javascriptchange
event, when the the state of a checkbox changes, and thepush()
method to add the checkbox value to thelist
array if checked, or thegrep()
method to remove checkbox values for checkboxes that, upon change, are unchecked.And for good measure, a vanilla Javascript version which…
…uses
querySelectorAll()
to collect the target checkboxes thenforEach()
to iterate the collection in order to add achange
event listener to each. Upon thechange
event the checkbox value ispush()
‘ed to thelist
array if the checked state of the checkbox istrue
, and, alternatively, remove the checkbox value from thelist
array if the checked state of the checkbox isfalse
. Array methodfilter
is used to remove unchecked box values from thelist
array.IF you need to send the order array data to the server, using the form containing the checkboxes, below is another approach to recording the order checkboxes are checked.
First notice the checkbox names have been changed from
name="mycheck"
toname="mycheck[]"
to make use of server-side array creation/modification, such as PHP.With that in place
querySelectorAll()
andforEach()
to collect the target checkboxes then iterate the collection in order to add achange
event listener to each.A
change
event handler is used to capture a checked state change for each targeted checkbox. Upon checked state change the number of already checked state checkboxes are counted usingquerySelectorAll()
attribute selectors along with modifier^=
and pseudo-class:checked
. The count is reduced by one to determine the next available array index.If the checked state changes to true, the next available array index is added to the checkbox name attribute.
If the checked state changes to false, the target checkbox previously assigned index is captures, the checkbox name is updated to remove the index, and the rest of the checked checkboxes’ indexes are updated to reflect the removal of one from the order of selections. Only the checkboxes with an index greater than the target index need to be updated.
match()
and a regular expression are used—in the the case of an unchecked state, which means the checkbox was previously checked—to capture the previously assigned index for: 1) capture the target checkbox index to determine which already checked checkboxes need their index decremented, and 2) when looping checked checkboxes in order to decrement all checkboxes having indexes greater than the target index.If you’re using PHP on the server to access this array, simply:
And if you need to use the order array in the browser, before the form is uploaded: