Display radio button list based on another multiple selection field in real time

This might be useful or not but I believe it's worth mentioning.

Scenario: I have an object crew with a one to many connection to the object Account (crew members). I also want, when I create or edit a crew, to nominate a crew manager only along the crew members. I also want this to happen real time: when I add / remove members through the drop down list (crew members), I want the crew manager field (which is a radio button list) to have available only the crew members selected.

The code:

// FUNCTION TO PROVIDE RADIO OPTIONS IN FORM DEPENDING ON A MULTIPLE DROP DOWN LIST
function radioDependancy(view, dropDownField, radioField){
var keys = [];
var values = [];
$("#connection-picker-radio-" + radioField + " input").each(function(index, elem){
keys.push($(this).val());
});
$("#connection-picker-radio-" + radioField + " span").each(function(index, elem){
values.push($(this).text());
});
var result = [];
keys.forEach((key, i) => result.push({"id" : key, "name" : values[i]}));
$("#connection-picker-radio-" + radioField +" .control").remove();
$("#"+view+"-"+dropDownField).on("change paste keyup", function() {
$("#connection-picker-radio-" + radioField +" .control").remove();
if($(this).val() != null){
$(this).val().forEach(function(value) {
$("#connection-picker-radio-" + radioField).append('<div class="control"><label class="option radio"><input name="' + view + '-' + radioField + '" type="radio" value="'+ value +'">&nbsp;<span>'+ result.find(x => x.id === value).name +'</span></label></div>');
});
}
});
}

// CALL THE FUNCTION ON THE FORM RENDER. field_yy is the drop down, field_zz is the radio button list
$(document).on('knack-view-render.view_xx', function(event, scene, record) {
radioDependancy("view_xx", "field_yy", "field_zz");
});

A note: every time there is an update on the drop down selection (.on("change paste keyup) I delete all the radio button list and recreate it. This is by design, as it resets the "checked" status (if any) of the selected item in the list and so forces the user to check it again (as it is a mandatory field).

Of course in other scenario, instead of doing so, it could be better to just add / remove the newly added / removed option. This require some more code and supposedly adding an ID for each item created (div, labels, span, ...).

Please comment, advice, fork.
Ciao!
D.

1 Like