How to set the value of the `data` attribute to` option` when using the `option` binding for knockout

In the documentation knockout he mentions optionsAfterRender . I tried to add the value of the data attribute without success.

Here is a sample from a document:

 <select size=3 data-bind=" options: myItems, optionsText: 'name', optionsValue: 'id', optionsAfterRender: setOptionDisable"> </select> <script type="text/javascript"> var vm = { myItems: [ { name: 'Item 1', id: 1, disable: ko.observable(false)}, { name: 'Item 3', id: 3, disable: ko.observable(true)}, { name: 'Item 4', id: 4, disable: ko.observable(false)} ], setOptionDisable: function(option, item) { ko.applyBindingsToNode(option, {disable: item.disable}, item); } }; ko.applyBindings(vm); </script> 

Here, what I tried but did not work, but also there were no errors.

 setOptionDisable: function(option, item) { $(option).text(''); // this will blank out the text in options $(option).data('test', '123'); // but this won't do anything at all. $(option).attr('data-test', '123'); // this worked as pointed out by Matt } 
+1
source share
1 answer

jQuery actually assigns data attr , but does not appear on the DOM element because jQuery stores it in the internal data structure. If you log the latest attr data, you will get a value, but you will not see it in the DOM.

Example: https://jsfiddle.net/kyr6w2x3/83/

But if you use attr() , it also updates the dom attribute.

Example https://jsfiddle.net/kyr6w2x3/84/

+2
source

All Articles