Dynamically setting a reference variable using another variable

kali
Tera Contributor

Hi All,

 

There is a variable select box based on the select box selected a reference variable should shown some dropdown values. What is the best approach in this , if possible please provide a sample code.

 

Thanks

1 REPLY 1

Yashsvi
Kilo Sage

Hi @kali,

please check below client script:

// Client Script - onChange script for Category field
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === '') {
        return;
    }

    // Assuming 'Category' field sys_id is 'category_field_sys_id' and 'SubCategory' is 'subcategory_field_sys_id'
    var categoryField = g_form.getControl('category_field_sys_id');
    var subCategoryField = g_form.getControl('subcategory_field_sys_id');

    // Clear existing options in SubCategory field
    subCategoryField.innerHTML = '';

    // Fetch options for SubCategory based on selected Category
    var subCategoryOptions = getSubCategoryOptions(newValue); // Replace with your logic

    // Populate SubCategory options
    subCategoryOptions.forEach(function(option) {
        var optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.label;
        subCategoryField.appendChild(optionElement);
    });

    // Optionally set the first option as selected
    if (subCategoryOptions.length > 0) {
        subCategoryField.value = subCategoryOptions[0].value;
    }
}

function getSubCategoryOptions(selectedCategory) {
    // Example function to fetch SubCategory options based on selected Category
    var options = [];

    switch (selectedCategory) {
        case 'Hardware':
            options = [
                { value: 'laptop', label: 'Laptop' },
                { value: 'desktop', label: 'Desktop' }
            ];
            break;
        case 'Software':
            options = [
                { value: 'os', label: 'Operating System' },
                { value: 'application', label: 'Application Software' }
            ];
            break;
        // Add more cases for other categories as needed
    }

    return options;
}

Thank you, please make helpful if you accept the solution.