Created
June 24, 2022 08:37
-
-
Save vmrfriz/5589f79487ef88bb9686054915490dbc to your computer and use it in GitHub Desktop.
JavaScript helper functions
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
/** | |
* Get form data as object | |
* | |
* Example: | |
* document.getElementsByTagName('form')[0].query(); | |
* > {"name": "John Doe", "phone": "+79876543210"} | |
*/ | |
HTMLFormElement.prototype.object = function() { | |
return Object.fromEntries(new FormData(this).entries()); | |
}; | |
/** | |
* Get form data as json string | |
* | |
* Example: | |
* document.getElementsByTagName('form')[0].json(); | |
* > "{\"name\": \"John Doe\", \"phone\": \"+79876543210\"}" | |
*/ | |
HTMLFormElement.prototype.json = function() { | |
return JSON.stringify(this.object()); | |
}; | |
/** | |
* Get form data as query string | |
* | |
* Example: | |
* document.getElementsByTagName('form')[0].query(); | |
* > "name=John%20Doe&phone=%2B79876543210" | |
*/ | |
HTMLFormElement.prototype.query = function() { | |
return new URLSearchParams(new FormData(this)).toString(); | |
}; | |
/** | |
* Make form elements disabled/enabled | |
* | |
* Example: | |
* document.getElementsByTagName('form')[0].disable(); // all form elements has disabled | |
* > undefined | |
* document.getElementsByTagName('form')[0].disable(false); // all form elements has enabled | |
* > undefined | |
*/ | |
HTMLFormControlsCollection.prototype.disable = function (makeDisabled) { | |
makeDisabled = (typeof makeDisabled == 'undefined') || makeDisabled ? true : false; | |
Array.from(this).forEach(function (_this) { | |
if (makeDisabled) _this.disabled = 'disabled'; | |
else _this.removeAttribute('disabled'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment