jQuery convert checkbox selections to array

后端 未结 2 757
闹比i
闹比i 2021-01-27 12:08

I have an HTML like this:

  • 2条回答
    •  误落风尘
      2021-01-27 12:59

      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:

      const array = {
        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);
      });
      
      
      

    • 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);
      });
      
      
      
    提交回复
    热议问题