Thursday, April 5, 2012

jquery to serialize only elements within a div


I would like to get the same affect as jQuery.serialize() but I would like to return only the child elments of a given div.



sample result:




single=Single2&multiple=Multiple&radio=radio1


Source: Tips4all

4 comments:

  1. No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

    $('#divId *').serialize();


    Check http://jsbin.com/azodo for a demonstration (http://jsbin.com/azodo/edit for the code)

    ReplyDelete
  2. You can improve the speed of your code if you restrict the items jQuery will look at.

    Use the selector :input instead of * to achieve it.

    $('#divId :input').serialize()


    This will make your code faster because the list of items is shorter.

    ReplyDelete
  3. Try also this:


    $('#divId').find('input').serialize()

    ReplyDelete
  4. jitter's solution helped me from a more generic viewpoint. Clicking a link, finding it's parent div and then serializing:

    //$(this) is a "click"able item within the div
    var divid = $(this).closest('div').attr('id);
    var data = $('#'+ divid+ ' *').serialize();

    ReplyDelete