jQuery serialize HTML5 data attributes

Sergey Telshevsky picture Sergey Telshevsky · Aug 24, 2012 · Viewed 12.4k times · Source

Couldn't find this anywhere, maybe someone knows or can make a suggestion.

I had a form with lots of <inputs>, I wanted to send that form with jQuery $.ajax functionality, so I did $('#myform').serialize() and send this as json.

Now my form is more advanced and has HTML5 data- attributes, that I want to send too, but .serialize() doesn't see them.

I tried putting them in <form> tag, <input> tags - nothing works.

What is the best practice to grab them and send with all the form data? I know about .serializeArray(), but how do I get all of the data- attributes that my <form> tag has attached serialized?

Answer

Sergey Telshevsky picture Sergey Telshevsky · Aug 24, 2012

Here's how it can be done. It might not be the best way, but it works the way it should work.

http://jsfiddle.net/Bvzqe/12/

HTML:

<form id="frm" data-id="123" data-list[one]="first" data-list[two]="second">

The serialization:

    var form = $('#frm');
    var dataarr = new Array();
    for(var i in form.data()) {
        var subarr = new Array();
        subarr['name'] = i;
        subarr['value'] = form.data()[i];
        dataarr.push(subarr);
    }
    var serialized = $.param(form.serializeArray().concat(dataarr));

It even allows you to have arrays of data- attributes such as

data-list[one]="first" data-list[two]="second"

URL encoded it may seem wrong, as it escapes square brackets, but I've tested this on the server side - it parses everything exactly as it should.

This is only for those that don't want to use <input type="hidden">