Brad
Brad

Reputation: 12262

Looping thru checked checkboxes and creating multi dimensional array

I have a series of checkboxes, meals and products. I am able to check each one and find the name and value. What I want to do and unable to do is create an array, the array index would be the name of the checkbox and the value would be the value of the checkbox that was checked.

$("#recipe-filter-form").submit(function(e) {
    e.preventDefault();

    var categories = [];
    var i = 0;

    $('.category-checkbox').each(function (index, value) {
        var checkboxName = $(this).attr('name');
        var checkboxValue = $(this).val();

        // if checkbox is checked
        if ($(this).is(':checked'))
        {
            categories[checkboxName][i] = checkboxValue;
            i++;
        }

    });

    console.log(categories);
});

This loops thru each checkbox, if it is checked, lets get the name and value.

I added an index i to the array in hopes of it working but it returns an error: TypeError: Cannot set property '0' of undefined

HTML

<form action="" method="get" id="recipe-filter-form">
    <ul>
        <li>
            <label class="check" data-category="appetizers">
            <input type="checkbox" name="meal" value="appetizers" class="category-checkbox"> Appetizers</label>
        </li>
        <li>
            <label class="check" data-category="beverages">
            <input type="checkbox" name="meal" value="beverages" class="category-checkbox"> Beverages</label>
        </li>
    </ul>

    <ul>
        <li>
            <label class="check" data-category="sides">
            <input type="checkbox" name="products" value="sides" class="category-checkbox"> Sides</label>
        </li>
        <li>
            <label class="check" data-category="soups">
            <input type="checkbox" name="products" value="soups" class="category-checkbox"> Soups</label>
        </li>
    </ul>

    <button type="submit" class="button green secondary">Filter</button>
</form>

If every checkbox was checked, my expected output is:

array('meal' => array('appetizers', beverages'), 'products' => array('sides', 'soups')

Why do I want to create a multi dimensional array?

Because after the array is created, I will generate a string by looping thru the array by appending the array index, values for a string to look like:

meal=appetizers,beverages&products=sides,soups

Question: How do I alter my code to get the expected output as seen on the line above?

Upvotes: 0

Views: 264

Answers (1)

rrk
rrk

Reputation: 15846

I believe you were having problems in the code you posted.

  1. categories[checkboxName][i] here categories[checkboxName] is undefined in the first attempt. So it will cause error.

  2. i is not needed. Just use push().

You can use categories[checkboxName] = categories[checkboxName] || []; to initialize the variable as an array if it is undefined in the loop.

$("#recipe-filter-form").submit(function(e) {
  e.preventDefault();
  var categories = [];
  $('.category-checkbox').each(function(index, value) {
    var checkboxName = this.name;
    var checkboxValue = this.value;
    // if checkbox is checked
    if ($(this).is(':checked')) {
      categories[checkboxName] = categories[checkboxName] || []; //initialize if not exist
      categories[checkboxName].push(checkboxValue);
    }
  });

  console.log(categories);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="" method="get" id="recipe-filter-form">
  <ul>
    <li>
      <label class="check" data-category="appetizers">
        <input type="checkbox" name="meal" value="appetizers" class="category-checkbox">Appetizers</label>
    </li>
    <li>
      <label class="check" data-category="beverages">
        <input type="checkbox" name="meal" value="beverages" class="category-checkbox">Beverages</label>
    </li>
  </ul>

  <ul>
    <li>
      <label class="check" data-category="sides">
        <input type="checkbox" name="products" value="sides" class="category-checkbox">Sides</label>
    </li>
    <li>
      <label class="check" data-category="soups">
        <input type="checkbox" name="products" value="soups" class="category-checkbox">Soups</label>
    </li>
  </ul>

  <button type="submit" class="button green secondary">Filter</button>
</form>

Upvotes: 1

Related Questions