Friday 10 August 2018

Remove optionset values dynamically using Javascript



Remove Optionset Value or Two option set Value Using Javascript


Hi all,

In CRM community I read a question that how to remove the option from Two optionset field based on conditions.

Long back I tried to remove values from Optionset field but I never tried to remove from Two option set field.

So now I changed my code for Two option set as well.

Using this code, we can remove multiple values at a time.

So here is the code

var Seperator = ",";

function RemoveOptionsByText(Field, Options) {


    //------------------------------------------------------------------------
    // Parameters Field - Optionset field
    //              Options - Array or list of text of options to be removed (case insensitive)
    // Action Locates and removes the specified options
    // Returns true if successful, otherwise false
    //------------------------------------------------------------------------

    var result = false;

    if (Field!=null) {
        var obj = Xrm.Page.getControl(Field);
        var Text = new String();
        var chk = new String("");
        var ary;
        var i;

        Options = ListToArray(Options);
        if (Options != null) {
            for (var o = 0; o < Options.length; o++) {
                Text = Options[o];
                if (Text != null) {
                    Text = Text.toUpperCase();
                    ary = Xrm.Page.getAttribute(Field).getOptions();
                    for (i = 0; i < ary.length; i++) {
                        chk = new String(ary[i].text);
                        if (chk.toUpperCase() == Text) {
                            obj.removeOption(ary[i].value);
                            result = true;
                            break;
                        }
                    }
                }
            }
            if (!result && DEBUGGING) alert("No text matches found");
        }
        else {
            if (DEBUGGING) alert("No text provided for match in RemoveOptionsByText");
        }
    }
    return result;
}

function ListToArray(list) {

    //------------------------------------------------------------------------
    // Parameters list - delimited string or array
    // Action Converts list to an array
    // Returns array of items
    //------------------------------------------------------------------------

    if (!Array.isArray(list)) {
        if (list + "" == "") return null;
        list = list.toString();
        list = list.split(Seperator);
    }

    return list;
}

function OnLoad(){
// Your Condition
RemoveOptionsByText("new_testtwooptions","yes");   // Here I am removing Yes from Two options field
//RemoveOptionsByText("new_testtwooptions","no");   // Here I am removing No from Two options field
//RemoveOptionsByText("new_optionsetfield",["A","B"]);   // Here I am removing A,B Options from optionset field ()
}