0

I'm using jQuery to dynamically add new divs containing a few fields. I'm adding new tunes in this example of output:

<div id="uploadedTunes">
   <div class="tune">
     Title:<input type="text" name="Title">
     Length:<input type="text" name="Length"> 
   </div>
   <div class="tune">
     Title:<input type="text" name="Title">
     Length:<input type="text" name="Length"> 
   </div>
</div>

Is there a way to serialize only the fields in the div uploadedTunes (and not the whole form) ? And how do I serialize this so I have an array like this:

uploadedTunes{ tune { Title="highway to hell", Length="03:01" } }

Thank you for your help or clues!

2 Answers 2

2

DEMO: http://jsbin.com/aneme/4/edit

include the jquery json lib

http://jquery-json.googlecode.com/files/jquery.json-1.3.min.js

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


$(function() {  
  //define the array
  var tune = []; 
  //start looping
  $('#uploadedTunes .tune').each(function(i , e) { 
 //automatically add to each pair of tune elements an equal class name
   $(this).children().attr('class','tune_'+i);  
  //create and convert the array to JSON
  tune.push( $.toJSON( $('.tune_'+i).serializeObject() ) );
  });
  //join all tunes into one comma separated sting
  var uploadedTunes = tune.join(",");
  alert( uploadedTunes );
});

NOTE: Most people think that serializeArray() work only with FORM, this is not exactly true, it can work also without form by giving to each element you want serialize the same class! then serialize this class instead of form!

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks aSeptik! I'll try to iterate through the tunes to create a collection of tunes. Maybe with var els = $(this).find('.tune').get(); and then within each tune, getting each field.
you don't need to do that if you are using <input! the demo i provided to you is already working as expected! ;-) PS: if this solve your problem pls check the answer! ;-P
Well this solves only a part of my problem. The script as you made it outputs : Title=1&Length=2&Title=3&Length=4. I'm looking at JSON serialization so I would have something such as: "uploadedTunes": { "tune": [ {"Title": "1", "Length": "2"}, {"Title": "3", "Length": "4"} ] }
Awesome! In my attempt to make the json serialization plugin work I missed the part where you have first to serialize before serializing to JSON. Thank you aSeptik (I checked it as answer but maybe you should edit the post with what you included in the comment)
2

Use serializeArray() on #uploadedTunes.

For example:

  jQuery.ajax({
    data : jQuery.param(jQuery(this).serializeArray()),
    dataType : 'script', 
    type:'post', 
    url:'/path/to/somewhere'
  }); 

I'm not sure if it works on something else than a form.

4 Comments

I get an array of objects Title,Length,Title,Length instead of an array of tunes each containing a Title and Length..
Shouldn't I first iterate through each tune, set its fields in a new custom object and append it to to some var (array of objects) before serializing it?
hmm, you are doing something which wasn't the intention of html/usual form design. I guess it wouldn't be that hard to do something like that (deserialize the whole html structure, including the form contents). But why dont you change the name of the fields to adapt them to your needs. Rails does it the following way: "tune[0][name]", "tune[0][duration]", "tune[1][name]" ... --> tune => [{:name => ..., :duration => ...}, {:name => ... }]. of course something like that is pretty difficult to do it youself.
indeed I figured out it's pretty much restricted to a key/value pair. So I might go with JSON to serialize my collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.