I have picklist field in CRM Dynamics called 'Confirm' with the following values
- Yes
- No
- In Progress
There is also a default/standard empty value allowing us to reset the picklist selection.
How can I use JavaScript to check if the default empty value is present? Currently, when using the following code, two default options are added. How can I ensure only one is displayed?
- ---Select----
- ---Select---
- Yes
- No
- In Progress
function addBlankOptionToPicklistIfNotExists(formContext) {
var targetAttributes = [
"test_confirmpicklist"
];
targetAttributes.forEach(function(targetAttribute) {
var control = formContext.getControl(targetAttribute);
formContext.getControl(targetAttribute).removeOption(-1);
if (control) {
// check if the attribute value is null or undefined
var attribute = control.getAttribute();
var attributeValue = attribute.getValue();
if (attributeValue != null && attributeValue != undefined) {
// check if the picklist already contains a blank option
var options = attribute.getOptions();
var nullOptionExists = options.some(option => option.value == -1);
// If blank option doesn't exist, add it
if (!nullOptionExists) {
control.addOption({ value: -1, text: "--Select--" }, 0);
}
}
}
});
}
The ---Select--- option is not a real option, it is only a text/placeholder identifying the
nullvalue for the field. This option is available for the user when the attribute requirement level is not Business Required. In that case the user should have the option to clear the input field.You can check an attribute's requirement level by using
formContext.getAttribute(targetAttributeName).getRequiredLevel(). (See getRequiredLevel (Client API reference) | MS Learn).When the field is Business Required, the form only displays the ---Select--- prompt (it is not an option here) as long as no value has been selected yet. As soon as an option is selected the user cannot clear the field, because a value is required.
However, it is possible to clear a default value or undo the user's choice by using JavaScript. Just set the field's value to
null: