I have some validation rules built in for fields. So, when I click submit on a form, the error message pops up at the top. However, I want to move the validation/error from the top to the bottom of the form. How can I do this? I tried using JavaScript but it isn’t working.
Nevermind! This code works.
//change your view
$(document).on(“knack-view-render.view_xx”, function (event, view, data) {
Knack.$(#${view.key} form
).on(“submit”, function () {
setTimeout(() => {
if (Knack.$(“.kn-message.is-error”)) {
Knack.$(“.kn-submit”).after(Knack.$(“.kn-message.is-error”));
}
}, 1000);
});
});
Is it possible to have this automatically apply to ALL forms?
@JDWorleyKY just replace view_xx
with any
, and it will apply to all views.
I had to fix all the quotation marks to get this code to work. But, once i implement it, it cause all of my pages in my app to hang up with the spinny circle forever…
Console shows this error: Uncaught (in promise) Error: Syntax error, unrecognized expression: #${view.key} form
I guess its trying to apply this code to ALL views, not just new forms?
I just changed it to only apply to one specific view/form, and it still gives that same error
@StephenChapman Further update, I fixed the spacing errors in the code, and no longer get the error, but it still doesn’t work or seemingly do anything at all…
Corrected code:
//makes errors show at bottom of form instead of top
$(document).on(‘knack-view-render.view_2895’, function (event, view, data) {
Knack.$(#${view.key} form
).on(‘submit’, function () {
setTimeout(() => {
if (Knack.$(‘.kn-message.is-error’)) {
Knack.$(‘.kn-submit’).after(Knack.$(‘.kn-message.is-error’));
}
}, 1000);
});
});
I got the above code to work, but it’s unreliable because there’s an unpredictable delay in shifting the error message to the bottom of the form.
The below code should work on all form views without relying on the timeout function.
It uses a MutationObserver
to check when an error message is created.
$(document).on("knack-view-render.form", function (event, view, data) {
const $view = $(`#${view.key}`);
const $form = $view.find(`form`);
$form.on('submit', function () {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1 && node.matches('.kn-message.is-error')) {
observer.disconnect(); // Stop observing
$view.find(`.kn-submit`).before(node); // Insert error message before submit button
}
});
});
});
// Start observing the form container where `.kn-message.is-error` might appear
observer.observe($form[0], { childList: true, subtree: true });
});
});
Let me know how that goes for you!