Skip to content Skip to sidebar Skip to footer

Jquery Convert Checkbox Selections To Array

I have an HTML like this:
  • Solution 1:

    I would recommend storing the ids in an object instead of having an array of array. It's easier to work with. Something like this:

    constarray = {
      category: [],
      home: [],
    };
    

    Then, you can always transform into the desired form with some array manipulation:

    Object.entries(array).map(([taxomony, id]) => ({taxomony, id}))
    

    Here is the code to update the object when a checkbox is clicked:

    const array = {};
    
    $('[name^="pgggo-"]').on('click', function() {
      const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
      const id = attr.split('[')[0];
      const checked = $(this).prop('checked');
      
      array[taxonomy] = array[taxonomy] || [];
      const index = array[taxonomy].indexOf(id);
      index == -1 ? array[taxonomy].push(id) : array[taxonomy].splice(index, 1);
      
      console.log(array);
    });
    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="pgggo-list-taxon"><li><label><inputtype="checkbox"name="pgggo-category-sep-56[]"><divclass="icon-box"><divname="development">Development</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-14[]"><divclass="icon-box"><divname="food">Food (category)</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-home-sep-14[]"><divclass="icon-box"><divname="food">Food (home)</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-8[]"><divclass="icon-box"><divname="medical">Medical</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-1[]"><divclass="icon-box"><divname="uncategorized">Uncategorized</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-2[]"><divclass="icon-box"><divname="wordpress">WordPress</div></div></label></li></div>

    Or, instead of having to go through the trouble of handling duplicates and states. You can construct the array only when you need to use it:

    $('.sort-button').on('click', function() {
    
      const array = {};
      $('[name^="pgggo-"]').filter(':checked').each(function() {
        const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
        array[taxonomy] = array[taxonomy] || [];
        array[taxonomy].push(attr.split('[')[0]);
      });
      
      console.log(array);
    });
    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="pgggo-list-taxon"><li><label><inputtype="checkbox"name="pgggo-category-sep-56[]"><divclass="icon-box"><divname="development">Development</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-14[]"><divclass="icon-box"><divname="food">Food (category)</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-home-sep-14[]"><divclass="icon-box"><divname="food">Food (home)</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-8[]"><divclass="icon-box"><divname="medical">Medical</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-1[]"><divclass="icon-box"><divname="uncategorized">Uncategorized</div></div></label></li><li><label><inputtype="checkbox"name="pgggo-category-sep-2[]"><divclass="icon-box"><divname="wordpress">WordPress</div></div></label></li></div><buttonclass="sort-button">Show!</button><!-- for demo purposes -->

    Solution 2:

    You want to store/send the selected values in one array, right? So why you use unique names then for each checkbox?! ... if they belong together then name them appropriately like so:

    <inputtype="checkbox"name="pgggo-category-sep[]"value="56"><inputtype="checkbox"name="pgggo-category-sep[]"value="14"><inputtype="checkbox"name="pgggo-category-sep[]"value="8"><inputtype="checkbox"name="pgggo-category-sep[]"value="1"><inputtype="checkbox"name="pgggo-category-sep[]"value="2"><inputtype="checkbox"name="pgggo-home-sep[]"value="foo"><inputtype="checkbox"name="pgggo-home-sep[]"value="bar">
        //....
    

    Then they will be sent as an array on submit automatically, no further rearrangement needed ... or if you really want to do it the ajax way still, you can easily get all the ids for the category-checkboxes like so:

        $('[name="pgggo-category-sep[]"]').on('change', function () {
          let values = Array.from($('[name="pgggo-category-sep[]"]:checked'))
            .map(elem => $(elem).val())
        })
    

    Post a Comment for "Jquery Convert Checkbox Selections To Array"