marioizquierdo / jquery.serializeJSON

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Consider passing element name to custom type function.

yurikus opened this issue · comments

My use case: I have a text box managed by jquery.mask plugin. I would like serializeJSON() to return clean value. This requires a reference to the element.

Cheers!

My workaround:

<input data-value-type="masked" data-mask="000-00-0000" type="text" ... />
/**
 * We need to know which control are we looking at!
 */
$.serializeJSON.applyTypeFunc = function(name, valStr, type, typeFunctions) {
    var typeFunc = typeFunctions[type];

    if (!typeFunc) { // quick feedback to user if there is a typo or missconfiguration
        throw new Error("serializeJSON ERROR: Invalid type " + type + " found in input name '" + name + "', please use one of " + objectKeys(typeFunctions).join(", "));
    }
    return typeFunc(valStr, name);
},

$.serializeJSON.defaultOptions = {
    disableColonTypes: true,

    customTypes: {
        masked: function (value, name) {
            return $(`[name="${name}"`).cleanVal();
        }
    }
};

What version are you using? The latest version 3.2.0 already implements what you need 😄 (see Changelog).

    customTypes: {
        masked: function (str, el) {
            // str is the string value
            // el is the DOM element
            // $(el) is the jQuery element
        }
    }

Interesting, this is in ASP Net Core project with packages managed by libman. It uses this https://cdnjs.com/libraries/jquery.serializeJSON

EDIT: jsdelivr seems to have v3.2: https://www.jsdelivr.com/package/npm/jquery-serializejson

Resolved, closing

My bad. I realized I didn't properly release the last version v3.2.0. Making the tag and release now. Thanks!