Elland
Elland

Reputation: 117

Select binding 'optionsCaption' display only if certain condition is met

I have a KO.js script on my Magento2 checkout

return Component.extend({
        defaults: {
            template: 'Magento_NegotiableQuote/shipping-address/list',
            visible: addressList().length > 0,
            showOptionCaptionText:addressList().length > 1,
            rendererTemplates: [],
            AddressList: [],            
            DropdownComponentRendererIndex:50
        }

        /**
         * Render My Custom Component 
         */
        createRendererDropdownComponent: function() {
              var rendererTemplate, templateData, rendererComponent;

              rendererTemplate = utils.extend({}, DropdownRendererTemplate);

              templateData = {
                    parentName: this.name,
                    name: 'shipping-addressall-dropdown'
                };

              rendererComponent = utils.template(rendererTemplate, templateData);               
              this.selectedItem = ko.observable(); 

              this.selectedItem.subscribe(function(latest){
                  selectShippingAddressAction(latest);
                  checkoutData.setSelectedShippingAddress(latest,latest.getKey());
                  this.createNewRendererComponent(latest,0);
                  },this);

              utils.extend(rendererComponent, {
                    allAddress: ko.observableArray(this.AddressList),
                    selectedItem: this.selectedItem,
                    showOptionCaptionText:this.showOptionCaptionText,
                });  

             layout([rendererComponent]);                
             this.rendererComponents[this.DropdownComponentRendererIndex] = rendererComponent;


        }

enter image description here

<div class="field addresses">
    <div class="control">
       <select  class="select select2" name="shipping_address_id" data-bind="
        options: allAddress,
        optionsText:addressOptionsText,
        optionsCaption: '---Please Select Address --',
        value: selectedItem" afterRender="selectTwo()">
        </select>  

    </div>     
</div>

Is it possible that I can add an optionsCaption text based on a condition? I have attached an image below, If that value is false I want to remove optionsCaption text? So basically all I want is if there is only one item for selection on the dropdown then auto select it and if there is more than one option then display a placeholder text ---SELECT--- .

Upvotes: 1

Views: 596

Answers (1)

Marius
Marius

Reputation: 15216

I'm shooting in the dark here (haven't tested it), but I think you can make the options caption computed.

computedCaption: ko.computed(function () {
    return addressList().length > 1 ? 'Select address' : null;
})

then build your select like this

<select ... data-bind="
    ....
    optionsCaption: computedCaption(),
    ....
</select>

Upvotes: 3

Related Questions