Last active
August 29, 2022 22:47
-
-
Save Mykola-Veryha/5efdfaffced08a2a2fbbc0aaf456c928 to your computer and use it in GitHub Desktop.
Copy form values
This file contains hidden or 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
const getFormValuesObject = (selector) => { | |
const form = document.querySelector(selector); | |
const formData = new FormData(form); | |
const formValues = {}; | |
for (const [name, value] of formData.entries()) { | |
formValues[name] = value; | |
} | |
return formValues; | |
}; | |
const setFormValues = (selector, formValues) => { | |
const form = document.querySelector(selector); | |
let editorInstanceName = ""; | |
for (const [name, value] of Object.entries(formValues)) { | |
editorInstanceName = "edit-" + name.replace(/[\][_]+/g, "-").replace(/-+$/, ""); | |
if (typeof CKEDITOR.instances[editorInstanceName] !== "undefined") { | |
CKEDITOR.instances[editorInstanceName].setData(value); | |
} | |
// Do not edit edit "form_token", "form_id". | |
if (!name.startsWith("form_")) { | |
form.elements[name].value = value; | |
} | |
} | |
}; | |
// Example how to copy form values from first form to second one. | |
// On a browser tab with the first form copy the formValues object from browser console. | |
const formValues = getFormValuesObject("#formId"); | |
console.log(formValues); | |
// On a browser tab with the second form. | |
const formValues = "Put there your copied object"; | |
setFormValues("#formId", formValues); |
Author
Mykola-Veryha
commented
Aug 29, 2022
const setFormValues = (selector, formValues) => {
const form = document.querySelector(selector);
let editorInstanceName = "";
for (const [name, value] of Object.entries(formValues)) {
editorInstanceName = "edit-" + name.replace(/[\][_]+/g, "-").replace(/-+$/, "");
if (typeof CKEDITOR.instances[editorInstanceName] !== "undefined") {
CKEDITOR.instances[editorInstanceName].setData(value);
}
// Do not edit edit "form_token", "form_id".
if (!name.startsWith("form_")) {
form.elements[name].value = value;
}
}
};
// On a browser tab with the second form.
const formValues = "Put there your copied object";
setFormValues("form", formValues);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment