0

I wrote the following function that turns a div/Form into serialized object. I use this returned to pass into my database javascript calling methods.

Tater.prototype._formToObject = function(formData) {
    var p = {};

    jQuery.each(jQuery(formData).serializeArray(),function(i, e){
        p[e.name] = e.value;
    });
    return p;
};

The only issue is if I change my form to have a multiple select option, it only grabs the first value of the multiple selected. How would I extend this to allow for such behavior?

Zach Smith
  • 5,490
  • 26
  • 84
  • 139
  • This thread discusses using jquery to extract multiple values from a multiple select dropdown. basically jquery.val() returns an array with the values. https://stackoverflow.com/questions/11821261/how-to-get-all-selected-values-from-select-multiple-multiple/27781069 – tstrand66 Jun 25 '19 at 15:51
  • yes i get that concept. just hoping for example to extend the method i currently have – Zach Smith Jun 25 '19 at 15:54

1 Answers1

0

Try something along these lines to get the array of values. If you give us a working snippet of what you are doing it will be easier to adapt to what you want. Most likely you need to add a check for the multiple attribute on e (see comments below) else do the current logic that seems to be working in the below logic replace this with e for your scenario

`

Tater.prototype._formToObject = function(formData) {
    const p = {};
    jQuery.each(jQuery(formData).serializeArray(),function(i, e){
        //check for multiple attr
        e.getAttribute('multiple') == null ? 
            (p[e.name] = e.value) :
            (p[e.name] = $(e).val());
    });
    return p;
};

`

document.getElementById('multi').addEventListener('change', function () {
    //jquery
    this.getAttribute('multiple') != null && console.log($(this).val());
    //vanilla
    if(this.getAttribute('multiple') != null) {
      const arr = [], nodes = this.querySelectorAll(':checked');
      for(let i = 0; i < nodes.length; i++) {
          arr.push(nodes[i].value);
      }
      console.log(arr);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="multi">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

<!-- from https://www.w3schools.com/tags/att_select_multiple.asp -->
tstrand66
  • 968
  • 7
  • 11