0

I am writing a function called serializePost.

The function will never be called on a set of objects. only ever one object.

hence my question is;

do I need to do this.each or can I simply use this

Will this work:

(function($) {
    $.fn.serializePost = function() {
        var data = {};
        var formData = $(this).serializeArray();
        for (var i = formData.length; i--;) {
            var name = formData[i].name;
            var value = formData[i].value;
            var index = name.indexOf('[]');
            if (index > -1) {
                name = name.substring(0, index);
                if (!(name in data)) {
                    data[name] = [];
                }
                data[name].push(value);
            }
            else
                data[name] = value;
        }

        return data;
    };
})(jQuery);

2 Answers 2

2

No need to use .each(), and no need to wrap it either.

var formData = this.serializeArray();

Inside the plugin, this is already a reference to the jQuery object.

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

1 Comment

Cheers for the quick answer :) will accept asap, and cheers for the point about wrapping this.
2

You can observe the source of the .val() function which basically pops the first element off the selection chain and works with it:

var elem = this[0]

3 Comments

An interesting idea. But, If the user was infact passing in a chain of objects they are obviously making an error somewhere and would not get the desired result. hence is this not a bit of a waste?
@Hailwood: If this is something you'll solely be using, the end answer is: code it however you'd like. If this could and will potentially be used by others, code it to be "bulletproof", expecting every possible anomaly and acting accordingly. Most functions of jQuery that deal with single elements pop the first element off the chain and work with it, so it's not far-fetched to use the same behavior.
@Hailwood: Brad makes a good point here. Although it is extracting the DOM element, which isn't what you want, it does ensure that you're only dealing with one element in case multiple were mistakenly passed. You may want to use this.eq(0).serialize... for safety. @Brad +1

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.