Created
July 16, 2023 09:06
-
-
Save movahhedi/d12916e0bfb39628091dc1e2a09b240f to your computer and use it in GitHub Desktop.
A simple extension of JQuery for TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import $ from "jquery"; | |
declare global { | |
interface JQuery { | |
/** | |
* Serialize an html form to an object | |
* | |
* @param Additional Additional key-value pairs to append to the result | |
* @returns An object containing form data | |
*/ | |
SerializeFormToObject: (Additional?: any) => any; | |
/** | |
* Serialize an html form to JSON | |
* | |
* @param Additional Additional key-value pairs to append to the result | |
* @returns A JSON string containing form data | |
*/ | |
SerializeFormToJson: (Additional?: any) => string; | |
hasAttr: (attrName: string) => boolean; | |
} | |
} | |
$.fn.SerializeFormToObject = function (Additional = null) { | |
const o: any = {}, | |
a = this.serializeArray(); | |
$.each(a, function () { | |
if (o[this.name]) { | |
if (!o[this.name].push) o[this.name] = [o[this.name]]; | |
o[this.name].push(this.value || ""); | |
} else o[this.name] = this.value || ""; | |
}); | |
if (Additional) o.push(Additional); | |
return o; | |
}; | |
$.fn.SerializeFormToJson = function (Additional = null): string { | |
return JSON.stringify(this.SerializeFormToObject(Additional)); | |
}; | |
$.fn.hasAttr = function (attrName: string): boolean { | |
return typeof $(this).attr(attrName) !== "undefined"; | |
}; | |
Object.assign(window, { jQuery: $, $ }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment