D
D
Dmitry2015-10-14 21:42:13
JavaScript
Dmitry, 2015-10-14 21:42:13

How to bind knockoutjs DOM element attribute?

There is such a select

<select data-bind="value: productPrice">
<option data-price="2">Цена $2.00</option>
<option data-price="4">Цена $4.00</option>
</select>

There is a block next to it where I want to display related information like this:
Ваша цена <span data-bind="text: productPrice"></span>

With this binding, the text of the selected option is naturally displayed. I want to display the data-price attribute of the selected option.
How can this be done in knockoutjs?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2015-10-14
@splirit

For example. you can write a custom binding for this case

var viewModel = {
  productPrice: ko.observable()
};

ko.bindingHandlers.selectedAttribute = {  
    init: function(element, valueAccessor) {
        var attr = valueAccessor().attr,
            property = valueAccessor().property;

        function updateModel() {
            property(element.options[element.selectedIndex].getAttribute(attr));
        }
        
        element.addEventListener('change', updateModel);
        updateModel();
    }
};

ko.applyBindings(viewModel);

Live example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question