mercredi 20 septembre 2023

jQuery Multidimensional array in each loop with dynamic inputs

I have a search form with filter that has multiple input types, checkboxes and select. Also there is multiple forms on a single page so i create have a container that has a dynamic ID and feeds that value to the function as deal.

The problem I'm having is managing the checkboxes in the form. The checkboxes is grouped using the input names. All the data is collected but when there is multiple checkboxes selected only the last option gets passed on.

Example of HTML

<div class="filter__container" id="months_specials_filter">
  <button class="filter__triger_btn">Filter</button>
    <div class="filter__wrapper">
      <div class="filter__colm star_rating col-3">
        <h4>Property rating</h4>
        <select name="class" id="class">
          <option value="">Select Option</option>
          <option value="1605">2 Star</option><option value="1586">3 Star</option><option value="1593">4 Star</option><option value="1601">5 Star</option><option value="1595">Not Star Graded</option>
        </select>                  
      </div>
      <div class="filter__colm room_type col-3">
        <h4>Room Types</h4>
        <select name="room-type" id="room-type">
          <option value="">Select Option</option>
          <option value="3784">Double</option><option value="3782">Single</option><option value="3785">Triple</option><option value="3783">Twin</option>
        </select>
      </div>

      <div class="filter__colm child_friendly col-3">
        <h4>Child Friendly</h4>
        <label><input type="checkbox" value="3787" name="child-friendly" id="child-friendly"> Children Allowed</label>
        <label><input type="checkbox" value="3786" name="child-friendly" id="child-friendly"> Infants Allowed</label>
      </div>

      <button id="months_specials_apply_filter" class="filter__sumbit_btn">Apply Filter</button>  
  </div>
</div>

jQuery

var filters = {};
$('#' + deal + '_filter :input').each(function(index,elem){

  filters[elem.name] = {};
  if (elem.name != "") {
    if (elem.type == 'checkbox') {
      if($(this).prop("checked") == true){
        filters[elem.name] = elem.value;
      }
    } else {
      filters[elem.name] = elem.value;
    }
  }
  
});

I have tried using .map and .push but the variable kept getting replaced for the checkboxes. Sure its just a simple thing I'm missing. I mainly work in server side code so not that familiar with Javascript / jQuery.




Aucun commentaire:

Enregistrer un commentaire