Page 1 of 1

Show and validate fields on checkbox selection

Posted: Mon Jan 03, 2022 4:55 pm
by Timo
Hi,

I have a requirement for showing and hiding some text input objects depending on checkbox selection (checked or uncheck).
Once the user ticks a checkbox, these objects, initially hidden, are displayed and when the checkbox is unticked, they are set to hidden.
Also, when the form is saved, there should be a check if all those fields are filled in.

I guess I could use some nuShow(), nuHide() calls etc. but was wondering if there was a more elegant way?

Re: Show and validate fields on checkbox selection

Posted: Mon Jan 03, 2022 8:52 pm
by kev1n
Hi Timo

You could add a custom attribute to all objects that you want to hide/show/validate. E.g. an attribute with name "data-obj-group"
attribute.jpg
In the form's Custom Code:

Code: Select all


// Hide all objects with attribute "data-obj-group" when the form opens or the checkbox is not ticked
displayObjGroupFields(); 

// Get an array with the Id of those objects
function getObjGroupFields() {
    
    let arr = $.map($('[data-obj-group]'), function(n, i) {
      return n.id;
    });  
    
    return arr;
}

function displayObjGroupFields() {
    nuShow(getObjGroupFields(), nuGetValue('checkbox_id') === true); // checkbox_id --> replace with your checkbox Object Id
}
Add an onclick event to the checkbox and call displayObjGroupFields();


The validation :

Code: Select all

function nuBeforeSave() {

    let m = '';
    for (const element of getObjGroupFields()) {
        if (nuGetValue(element) === '') {
            m += $('#label_' + element) + " cannot be left blank. <br>";
        }
    }

    if (m !== '') {
        nuMessage(m);
        return false;
    }
    return true;
 
}