You are viewing limited content. For full access, please sign in.

Question

Question

Modern ("New") Forms Designer LF 12 - hide or show a checkbox based on a radio button selection

asked on May 7

I currently don't see a way in the Field Rules to hide/show a checkbox option within a checkbox group. So, I thought I would try Javascript but it appears to only work in the web browser dev console, and not in the Inline Javascript of the form. I know that Javascript in the Modern Forms designer uses a "sandboxed" model, and I tried some simple tests with LFForm.hideFields({fieldId: 347}), for example, but I can't figure out how to get the same functionality as this:

(function () {
    function toggleCheckboxOption() {
        let selectedLabel = "";

        // Step 1: Find the <label> for "I am requesting for" and get the selected radio button's label
        const $groupLabel = $("label.field-label:contains('I am requesting for')");

        if ($groupLabel.length > 0) {
            // Step 2: Find the radio group related to the label
            const $radioGroup = $groupLabel.closest("fl-radio");

            // Step 3: Find the checked radio button
            const $selectedRadio = $radioGroup.find("input[type='radio']:checked");

            if ($selectedRadio.length > 0) {
                // Step 4: Get its ID and find the matching label's <span>
                const radioId = $selectedRadio.attr("id");
                const $labelSpan = $radioGroup.find("label[for='" + radioId + "'] span");

                if ($labelSpan.length > 0) {
                    selectedLabel = $labelSpan.text().trim();
                }
            }
        }

        console.log("✅ Scoped selected label:", selectedLabel);

        // Step 5: Target the "New User Accounts" checkbox based on its value
        const $targetCheckbox = $("input[type='checkbox'][value='New_User_Account']").closest('.option');

        if (selectedLabel === "New Employee") {
            $targetCheckbox.show();
        } else {
            $targetCheckbox.hide();
            $targetCheckbox.find('input').prop('checked', false);
        }
    }

    // Run initially
    toggleCheckboxOption();

    // Re-run when any radio button is changed
    $(document).on('change', "input[type='radio']", toggleCheckboxOption);
})();

 

0 0

Answer

SELECTED ANSWER
replied on May 7

Hi @████████, I will share with you a solution, but you need to readapt to your scenario. Because I build this in a Test form. 

If I understood your question correctly, I'll restate what the code I'm about to share below does:

I created a Radio Button with ID 1 (in your scenario you must change for the real one), and within the basic options, I checked the Assign Values ​​to Choices checkbox (this allowed me to be more specific when locating the value for the radio button). For this test, I set the following options:

Label: Choice 1, Value: Choice 1 * I didn't use this one; I just left it there as part of the example so you could observe the behavior of the other options.
Label: New Employee, Value: NE_Choice
Label: Employee Termination, Value: NE_Choice

You can see it better in this image if you have any questions:

Create a Checkbox with ID 2(you can change this for your real one). Just like I did with the Radio Button, I added some sample content:

Label: Choice 1, Value: Choice_1
Label: New User Account, Value: New_User_Account
Label: Employee Termination, Value: Employee_Termination

You can also see it in this image:

And then put this JavaScript Code in your JS Section: 

/*****************************************************************
 *  Radio Button (Field ID 1)                Checkbox (Field ID 2)
 *  ─────────────────────────────────────    ────────────────────────────────────
 *  Label                Value              Label                 Value
 *  ─────────────────────────────────────    ────────────────────────────────────
 *  New Employee         NE_Choice          New User Account      New_User_Account
 *  Employee Termination ET_Choice          Employee Termination  Employee_Termination
 *
 *  Behaviour:
 *    • Both checkbox options are hidden on load.
 *    • Selecting “New Employee”      → shows “New User Account”.
 *    • Selecting “Employee Termination” → shows “Employee Termination”.
 *****************************************************************/

const radioField    = { fieldId: 1 };
const checkboxField = { fieldId: 2 };

const checkboxOptions = {
  newAccount : { label: "New User Account",     value: "New_User_Account" },
  termination: { label: "Employee Termination", value: "Employee_Termination" }
};

/* -- Main sync function ----------------------------------------------------- */
async function syncCheckboxOptions() {
  /* 1 – Get current radio value (e.g. “NE_Choice”). */
  let radioValue = await LFForm.getFieldValues(radioField);
  if (radioValue && typeof radioValue === "object") radioValue = radioValue.value;

  /* 2 – Always remove both target options first. */
  await LFForm.changeFieldOptions(
    checkboxField,
    Object.values(checkboxOptions),
    "remove"
  );

  /* 3 – Decide which option (if any) to add back in. */
  let optionToAdd = null;
  if (radioValue === "NE_Choice") {
    optionToAdd = checkboxOptions.newAccount;
  } else if (radioValue === "ET_Choice") {
    optionToAdd = checkboxOptions.termination;
  }

  if (optionToAdd) {
    await LFForm.changeFieldOptions(checkboxField, [optionToAdd], "add");
  }

  /* 4 – Clear orphaned selections if the user had already checked something. */
  const current = await LFForm.getFieldValues(checkboxField);
  const allowed = optionToAdd ? [optionToAdd.value] : [];
  if (current?.value?.some(v => !allowed.includes(v))) {
    await LFForm.setFieldValues(checkboxField, { value: [] });
  }
}

/* Run once on load and again whenever the radio field changes. */
syncCheckboxOptions();
LFForm.onFieldChange(syncCheckboxOptions, radioField);

I hope this is what you're looking for. Let me know if it works for you.

Radio-Check.gif
2 0
replied on May 8 Show version history

Hi Luis,

It looks like this should work. Let me try to modify it for my purposes and get back to you.

Thanks!

 

Just a follow-up: I was able to use your example and it works great. Thanks!

1 0
replied on May 10

I am glad to have been able to help. Thank you! 

0 0
replied on May 12

Luis,

The function apparently works to add or remove a checkbox option within the checkbox control. Although it does work as intended, there is an unintended consequence; when the user fills out the form, it acts and looks like it should, but the checked boxes in that control group do not keep their values when the next person in the routing receives the form. In testing, I checked several boxes but none of them remained checked in the subsequent tasks.

Do you have any suggestions? For now, I have deactivated the code.

Thanks!

Mike

 

0 0
replied on May 12

Hi Mike,
Thanks for bringing this detail to my attention. Let me check what might be going on. When the form is assigned to a User Task, the variables retain the previously selected options, but when the form is saved, it doesn't save any checkbox options to the repository. I'll let you know if I find the problem and the solution.

1 0
replied on May 12

Hi Mike,
After several tests, there's certainly something strange when making a copy of the form (assuming you duplicate the main form and then create the Review form from it, or simply duplicate it to do something else). The values, despite being displayed, aren't saved in the form when it goes to the repository. I'm still investigating what could be causing this.
However, I noticed something else you can do, as it worked for me. This is a workaround.
Only use the JavaScript code in the form where you're going to capture that behavior between the Radio Button and the Checkbox for the first time.
In the Review form (don't use the JavaScript), since I don't think you'll need it in the review for now. If so, there's no problem keeping it. But I recommend not leaving it in the Review form.
Now here's where the trick comes in. If you duplicated the main form to create the Review variant, in the Review form, delete the Radio Button and Checkbox objects in question from the form, save the changes, then go to the Variables tab of the form tools and drag and drop your Radio Button and Checkbox back onto the form, and save the changes.
Following these steps will ensure that the values ​​and data in the form are saved without problems. Test it and let me know.
P.S.: Don't ask me why, since I'm still investigating what happened there (in the case where you duplicated the main form), this doesn't happen when you create the Review form from scratch. If I find the exact cause, I'll let you know.

0 0
replied on May 12

Hi Luis,

 

I actually haven't tested what happens when saved to the repository yet. I'm just testing with the same form being routed to a subsequent task and seeing that checked boxes are no longer checked.

0 0
replied on May 12

Could you export and share your process with me? You can send it directly to luis@aviditytechnologies.com if you prefer.

0 0

Replies

replied on May 8

I have a form where I set-up multiple checkboxes and used CSS to format them so that they looked like a single checkbox field, and then used the Field Rules to disable and enable them.  I did a demo of this form during a Laserfiche Champion call last year, and the recording of that demo is available on Aspire: https://laserfiche.csod.com/ui/lms-learning-details/app/video/aa03ce3a-2f88-48c1-875f-24d9a8de775e#t=2

2 0
replied on May 8

Hi Matthew,

Thanks for the link to the video. I like your approach of using separate check boxes instead of a checkbox group, as it makes the usage of field rules possible. I will likely use something like this going forward, but for the current task at hand I think I'll explore Luis' code example.

Thanks!

2 0
replied on May 8

Oh, for sure - @████████'s example is fantastic!

2 0
You are not allowed to follow up in this post.

Sign in to reply to this post.