views:

50

answers:

2

Hi,

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!

A: 

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.

reto
I get an array of objects Title,Length,Title,Length instead of an array of tunes each containing a Title and Length..
teebot.be
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?
teebot.be
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.
reto
indeed I figured out it's pretty much restricted to a key/value pair. So I might go with JSON to serialize my collection.
teebot.be
+1  A: 

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!

aSeptik
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.
teebot.be
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
aSeptik
teebot.be
Try this http://jsbin.com/aneme/4/edit and let me know! ;-)
aSeptik
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)
teebot.be
sure!, i have changed it! ;-)
aSeptik