Search code examples
htmljqueryjson

Passing key-value pairs of multiple related form fields as a JSON string


How can I pass the key-value pairs of these related dropdown lists as a JSON string using JQuery? (For instance like: {"32":"3","4":"1"} )

<select name="32" rel="select_items">
...
...
</select>

<select name="4" rel="select_items">
...
...
</select>

I'm aware of the possibilty to use JQuery's serializeArray(), but I'm not sure how to use this function on the related form items only, rather than the whole form.

Thanks for your support.


Solution

  • Assuming I understand your question correctly: that you want ALL your options serialized into JSON I would do it like this

    HTML

    <select name="32" rel="select_items">
      <option value=one>1</option>
      <option value=two>2</option>
    </select>
    
    <select name="4" rel="select_items">
      <option value=three>3</option>
      <option value=four>4</option>
    </select>
    

    jQuery

    var output = {};
    $("select option").each(function(){
         var value = $(this).val();
         output[value] = $(this).html();
    });
    document.write(JSON.stringify(output));
    

    If you want just the selected ones you can do that with:

    var output = {};
    $("select option:selected").each(function(){
          var value = $(this).val();
          output[value] = $(this).html();
    });
    

    or you could, like you described yourself, just use serializeArray();

    JSFiddle