Changing the Background Color of a Form depending on it's state

I have a form that toggles a single Radio Field. I want to swap out one of the components CSS-Classes from “highlight-red” to “highlight-green” depending on the value of the field. It’s important to swap the class for the whole component and not just a field. I tried my luck with ChatGPT but my Scripts didn’t really work.

Dynamically Changing CSS Based on Form Field Values

This script dynamically updates the CSS of an element (.ds-status-selector) based on the value of a field (field_1345). It works by retrieving the initial value from component_85 and, after the form is saved, confirming the updated value from component_96.

How It Works

  1. Initial State Setup

On page load, the script retrieves the value of field_1345 from component_85 and applies the appropriate CSS class (.confirmed or .not-confirmed) to the .ds-status-selector element.

  1. Save Button Click Handling

When the save button (.af-form-submit) is clicked, the script:

• Waits for a short delay (500ms) to ensure the backend updates the value.

• Retrieves the updated field_1345 value from component_96.

• Applies the correct CSS class based on the updated value.

Code

CSS Classes:

.confirmed {
    margin-bottom: 10px;
    border: 1px solid #8b9e74 !important;
    padding: 1%;
    margin: 2% 2%;
    background-color: #d9ead3 !important;
    border-radius: 5px;
}

.not-confirmed {
    margin-bottom: 10px;
    border: 1px solid #b54134 !important;
    padding: 1%;
    margin: 2% 2%;
    background-color: #f28b82 !important;
    border-radius: 5px;
}

JavaScript:

TB.render('component_85', function (data85) {
    function applyClass(isConfirmed) {
        const selector = document.querySelector(".ds-status-selector");
        if (selector) {
            selector.classList.remove("confirmed", "not-confirmed");
            selector.classList.add(isConfirmed ? "confirmed" : "not-confirmed");
        }
    }

    function getFieldValue85() {
        return data85.record && data85.record["field_1345"]
            ? data85.record["field_1345"]
            : null;
    }

    function getFieldValue96(callback) {
        TB.render('component_96', function (data96) {
            if (data96 && data96.record && data96.record["field_1345"]) {
                callback(data96.record["field_1345"]);
            }
        });
    }

    const initialValue = getFieldValue85();
    if (initialValue) {
        applyClass(initialValue === "confirmed");
    }

    data85.ele.find('.af-form-submit').on('click', function () {
        setTimeout(() => {
            getFieldValue96((updatedValue) => {
                applyClass(updatedValue === "confirmed");
            });
        }, 500);
    });
});

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.