skip to Main Content

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


  1. You can use this way

        var list = new Array();
        $('input').on("click", function (e) {
            if ($(this).is(':checked')) {
                list.push([$(this).val()]);
            }
            console.log(list);
    
        })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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">

    Hope it will be work 🙂

    Login or Signup to reply.
  2. 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 on click, 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.

    const checkedLog = [];
    
    $('input[type="checkbox"]').on("change", function(e) {
      if (this.checked) {
        checkedLog.push(this.value);
      }
      // only track order in which they were checked, not unchecked
    });
    
    $('button').on('click', function() {
      // get all actually checked values
      const vals = [];
      $('input:checked').each(function() {
        vals.push(this.value);
      })
    
      // sort actually checked values by last log entry
      const reverseLog = 
      vals.sort((a, b) => checkedLog.lastIndexOf(a) - checkedLog.lastIndexOf(b));
      console.log(vals);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <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" checked>
    
    <label for="check-3">check 3</label>
    <input type="checkbox" id="check-3" value="3" name="mycheck">
    
    <button>get sorted values</button>

    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.

    Login or Signup to reply.
  3. 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

    // Define an empty array
    let checks = [];
    
    // Bind each checkbox to the change event
    $('.chx').on('change', function() {
      // If the changed checkbox is checked
      if (this.checked) {
        // Add the checkbox's value to the array
        checks.push(+$(this).val());
      } else {
        // Otherwise add a negative value of the checkbox to the array
        checks.push(-$(this).val());
      }
      console.log(checks);
    });
    /* Added the negative numbers because there's two states a checkbox is in
    and if it's important to know the order of what was checked then it's 
    probably important to know what state each one is in as well.
    */
    <label for="check-1">check 1</label>
    <input type="checkbox" id="check-1" class='chx' value="1" name="mycheck[]">
    
    <label for="check-2">check 2</label>
    <input type="checkbox" id="check-2" class='chx' value="2" name="mycheck[]">
    
    <label for="check-3">check 3</label>
    <input type="checkbox" id="check-3" class='chx' value="3" name="mycheck[]">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  4. This answer assumes values are unique.

    When checked, push the value to an array.
    When unchecked, remove it from the array.

    const selections = [];
    $('[name="mycheck[]"]').on('change', function (){
      // if checked, add it to the array
      if (this.checked) {
        selections.push(this.value);
      } else {
        // if not checked, remove the value from the array
        const index = selections.indexOf(this.value);
        if (index > -1) selections.splice(index, 1);
      }
      console.log(selections);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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[]">
    Login or Signup to reply.
  5. Using jQuery on() method to capture the Javascript change event, when the the state of a checkbox changes, and the push() method to add the checkbox value to the list array if checked, or the grep() method to remove checkbox values for checkboxes that, upon change, are unchecked.

    var list = new Array();
    $('input').on("change", function(e) {
      let boxval = $(this).val();
      if ($(this).is(':checked')) {
        list.push(boxval);
      } 
      else {
        list = $.grep(list, function(item) {
         return boxval !== item;
        });
      }
      console.log(list);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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 for good measure, a vanilla Javascript version which…

    …uses querySelectorAll() to collect the target checkboxes then forEach() to iterate the collection in order to add a change event listener to each. Upon the change event the checkbox value is push()‘ed to the list array if the checked state of the checkbox is true, and, alternatively, remove the checkbox value from the list array if the checked state of the checkbox is false. Array method filter is used to remove unchecked box values from the list array.

    var list = [];
    document.querySelectorAll('input[name="mycheck"]').forEach(function (box) {
      box.addEventListener("change", function (evt) {
        let boxval = evt.target.value;
        if ( true === box.checked ) {
          list.push(boxval);
        }
        else {
          list = list.filter(function(val) {
            return boxval !== val;
          });
        }
        console.log(list);
      });
    });
    <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">
    Login or Signup to reply.
  6. 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" to name="mycheck[]" to make use of server-side array creation/modification, such as PHP.

    With that in place querySelectorAll() and forEach() to collect the target checkboxes then iterate the collection in order to add a change 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 using querySelectorAll() 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.

    // collect and loop inputs with name starting with "mycheck["
    document.querySelectorAll('input[name^="mycheck["]').forEach(function (cbox_change) {
    
      // add a change event listener to each checkbox
      cbox_change.addEventListener("change", function ({target: cbox_order}) {
    
        // determine the next available index
        let idx_add = document.querySelectorAll('input[name^="mycheck["]:checked').length - 1;
      
        // if changed checkbox check state is true (checked)
        if ( cbox_order.checked ) {
          // add next index to name attribute
          cbox_order.name = "mycheck[" + (idx_add) + "]";
        }
        
        // if changed checkbox check state is false (unchecked)
        else {
          // get target index already assigned when changed to true
          let idx_remove = parseInt(cbox_order.name.match(/^mycheck[([0-9]+)]$/)[1]);
          // remove index from name
          cbox_order.name = "mycheck[]";
          // loop all checked checkboxes to update indexes greater than target index
          document.querySelectorAll('input[name^="mycheck["]:checked').forEach(function (cbox_update) {
            // capture index to update
            let idx_update = parseInt(cbox_update.name.match(/^mycheck[([0-9]+)]$/)[1]);
            // if greater than target index, reduce by one
            if (idx_remove < idx_update) {
              cbox_update.name = "mycheck[" + (idx_update - 1) + "]";
            }
          });
        }
    
        // show name of all "mycheck" checkboxes
        document.querySelectorAll('input[name^="mycheck["]').forEach(function (cbox) {
          console.log(cbox.name);
        });
      });
    });
    <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[]">

    If you’re using PHP on the server to access this array, simply:

    <?php
    
    // get checked order array
    $mycheck = $_POST['mycheck'];
    // sort by key
    ksort($mycheck);
    
    ?>
    

    And if you need to use the order array in the browser, before the form is uploaded:

    let check_order = Array.from(document.querySelectorAll('input[name^="mycheck["]:checked'))
      .sort(function (aa, bb) {
        return aa.name.match(/^mycheck[([0-9]+)]$/)[1] - bb.name.match(/^mycheck[([0-9]+)]$/)[1];
      })
      .map(function (item) {
        return parseInt(item.value);
      })
    ;
    
    console.log(check_order);
    <label for="check-1">check 1</label>
    <input type="checkbox" id="check-1" value="1" name="mycheck[2]" checked>
    
    <label for="check-2">check 2</label>
    <input type="checkbox" id="check-2" value="2" name="mycheck[0]" checked>
    
    <label for="check-3">check 3</label>
    <input type="checkbox" id="check-3" value="3" name="mycheck[1]" checked>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search