lundi 14 décembre 2015

Create and store/add to an array from filtered checkbox values

I have a scenario where a long list of checkbox options are filtered in and out with a PHP/ajax query. So when a user checks one or more check boxes, the need is to create a list of what boxes the user has checked.

Using jQuery and .map(), I am able to create the initial list array of what checkboxes are checked. Easy enough.

var selected_checkboxes;

$( document ).on( 'click', '.checkbox_select', function() {
    var checkbox_selector = $( '.checkbox_select:checked' );

    selected_checkboxes = checkbox_selector.map( function(i, n) {
        return this.value;
    }).get();

    console.log(selected_checkboxes);
});

So here, we'll say I have a group of 10 checkboxes (Checkbox 1 - 10) and I check the first 3.

Console output ["Checkbox 1", "Checkbox 2", "Checkbox 3"]

The problem comes when you filter the view of checkboxes. Say you filter out all checkboxes other than Checkbox 3, 5 and 6. Checkbox 3 is still checked. Now if we check "Checkbox 5", our new list array will be as follows: ["Checkbox 3", "Checkbox 5"].

I know why it does that, but the needed result is to build upon what was previously checked prior to running the filter, which should look like ["Checkbox 1", "Checkbox 2", "Checkbox 3", "Checkbox 5"]. Almost like you're just adding to that initial array of values.

The checkboxes when filtered can't be hidden with hide/show since it's all an ajax based query.

Does anyone have any ideas how I could get an array to work like this? Any help would be hugely appreciated.

Aucun commentaire:

Enregistrer un commentaire