nhoyti
nhoyti

Reputation: 1997

How to add title in data-bind select option

I have been researching on how to add title in the option properties as my select tag is data-binded to dynamically generate option contents

                            <select class="form-control test" style="height:220px;" multiple="multiple" data-bind="options: $parent.InitiatorFields, optionsText: 'FieldDescription', optionsValue: 'FieldCode', selectedOptions: $root.selectedFromListRule "></select>

I wanted to happen something like this

<select class="form-control test" style="height:220px;" multiple="multiple" data-bind="options: $parent.InitiatorFields, optionsText: 'FieldDescription', optionsValue: 'FieldCode', selectedOptions: $root.selectedFromListRule ">
<option data-bind="attr {title: 'FieldDescription'}"></option>

is this possible?

Upvotes: 1

Views: 469

Answers (1)

Adrian
Adrian

Reputation: 1587

You can use optionsAfterRender which have been documented here.

If you need to run some further custom logic on the generated option elements, you can use the optionsAfterRender callback. The callback function is invoked each time an option element is inserted into the list, with the following parameters:

So a sample for what you want would be:

var VM = function(){
  this.options = ko.observableArray(["Option 1", "Option 2", "Option 3"]);
  this.selectedOptions = ko.observableArray(["Option 2"]);
  this.setTitle = function(option, item){
    ko.applyBindingsToNode(option, {attr: {title: "FieldDescription"}});
    // option.title = "FieldDescription"; // Or this line directly
  }
}

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select multiple="true" data-bind="options: options, selectedOptions: selectedOptions, optionsAfterRender: setTitle">

Upvotes: 1

Related Questions