Skip to main content
Kinetic Community

Combine two menus

This is an example of combining menu options from two menus into one menu.  The combine menu is sorted and duplicates are removed from the list.

Resolution

To use this javascript place this javascript into your request and call the "combineTwoMenus" function with the appropriate parameters.


/**
* DESCRIPTION Combine option values from 2 menus into one menu option list.
* @method combineTwoMenus
* @param source1 {String} The first menu field name.
* @param source2 {String} The second menu field name.
* @param destination {String} The field name to be populated with the combined menu options.
*/
<script>
  function combineTwoMenus(source1,source2,destination){
    var menu = new Array;

    //Source Questions
    var opts1 = K('field['+source1+']').options();
    var opts2 = K('field['+source2+']').options();
    opts2.shift();  //take off the empty first element
    opts1.shift();  //take off the empty first element
    
    //add menus together
    menu = opts1.concat(opts2);
    
   
    //Sort Array assending
    menu.sort(charOrdA);
    // OR Sort Array decending
    //menu.sort(charOrdD);

    //remove duplicates
    var non_duplidated_data = _.uniq(menu, 'label');

    //set menu into recieving field
    K('field['+destination+']').options(non_duplidated_data);

}


//Functions used to place all characters into lowercase inorder to correctly sort.
//Sort Accending
function charOrdA(a, b){
    if (a['value'] === undefined || b['value'] === undefined) return 0;
    a = a['value'].toLowerCase(); b = b['value'].toLowerCase();
    if (a>b) return 1;
    if (a <b) return -1;
    return 0;
}

//Sort Decending
function charOrdD(a, b){
    if (a['value'] === undefined || b['value'] === undefined) return 0;
    a = a['value'].toLowerCase(); b = b['value'].toLowerCase();
    if (a<b) return 1;
    if (a >b) return -1;
    return 0;
}

</script>