10

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?

11
  • 1
    You need to define how you expect these attributes to get serialised. Do you just want data-foo="bar" to get mapped to foo=bar ? Also, is there any reason they can't go into hidden input tags? Commented Aug 23, 2012 at 22:16
  • Since data- attributes can be called anything, you'll also need to specify which ones you want to serialize. Commented Aug 23, 2012 at 22:18
  • Technically - yes, I want to think of an easy way to do this, so that I could do $('#myform').serialize() and the string would have input values and data- attribute values serialized and escaped. It could be a custom function. Commented Aug 23, 2012 at 22:19
  • 2
    @Alnitak's idea of using hidden inputs seems like the right approach to me. Commented Aug 23, 2012 at 22:24
  • 1
    possible duplicate of: stackoverflow.com/questions/5560293/… Commented Aug 23, 2012 at 22:46

3 Answers 3

9

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">

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

3 Comments

This works and is the right way to go. I've used this sort of code in a couple of helper methods. A new "serializeDataArray()" jQuery extension and an AJAX post back method which includes three parts... the original form serialize array then serialize data attributes for both form and source/post back control. Not sure what the HTML 5 rules are on this but I think data attributes from both the (more global) form and (contextual) source element are necessary is most cases.
Thanks for reminding me you can just use a hidden input lol
Hello how to deserilize a JSON to data - attributes the reverse way
6

If at all possible you should store your additional values as hidden input fields (one per value) rather than as meta-data on other input fields. They'll then get serialized automatically as part of the form.

I won't write a serializer for you, as I think it's a bad idea. If you insist on sending the values to the browser as data- fields you could do this, though, to convert those data- fields into hidden inputs.

$('#myform:input').each(function() {
    var input = this;
    $.each($(input).data(), function(key, value) {
        $('<input>', {type: hidden, name: key, value: value}).insertAfter(input);
    });
});

Hey presto, hidden input fields that'll be automatically serialized!

Be aware that jQuery also uses .data() to store things like events. To avoid iterating over those objects you'd have to use the native DOM functions to retrieve the data- attributes, and not any data-related properties that have been stored on the elements.

15 Comments

Sorry, that just will not do. That is not the answer to my question, that is a workaround.
@Vlakarados yup, that's what I call a work around. You've invented a scheme for storing additional information in the form (because of minor concerns about page load times) that is not supported by W3C <form> tags and then complain when the means to serialise that data doesn't exist?! Hidden fields weren't invented "because there was no AJAX", they were invented because that's how you supply extra information in a form!
Gotta side with @Alnitak on this, the bandwidth introduced by additional inputs is incredibly trivial. Hidden inputs will also work regardless of whether javascript is enabled (or broken).
@Vlakarados you should note that I'm not getting any rep for this - I already hit the daily limit. I'm putting this much effort in because I seriously believe that your current implementation is incorrect.
I have to side the Sergey here. I'm running up against the same challenge right now. Even though using hidden input elements is considered the standard, de facto way of tacking on additional data to a form, the big problem inherent in that method is that one can no longer associate data-* values with a particular form element. That is to say, once serialized, you end up with a flat map whose structure does not represent associations. What I'm probably going to end up doing is to write my own serializer that creates a JSON tree of the form.
|
0

here is my func, get all data-* of element + support ignore array

Data2Params: function (el, ignoredAtt) {
    ignoredAtt = typeof ignoredAtt !== 'undefined' ? ignoredAtt : [];

    var data = {};
    for (var key in el.data()) {
        if (ignoredAtt.indexOf(key) === -1)
            data[key] = el.data(key);
    }
    return data;
}

Comments

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.