Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

data binding - knockout bind text label to dropdown value selected option text

Is there a simple way to bind the textbox of a div to change based on the text value of the selected option in a dropdown on the same page?

<div data-bind="text: dropdownValue"></div>
<select>
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>

Please note, I don't want to put the values into the select element using javascript. I'd like to bind to the value straight from the HTML. I can also include jQuery to make it work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was looking for similar functionality in something I was throwing together yesterday and couldn't find it, so I ended up just changing what I was storing in the value attributes. Sometimes that's the simplest solution.

Here's a quick and kind of ugly solution to the problem using jQuery:

HTML

<div data-bind="text: dropdownText"></div>
<select data-bind="value: dropdownValue" id="dropdown">
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>

JS

function ViewModel() {
    var self = this;
    this.dropdownValue = ko.observable();
    this.dropdownText = ko.computed(function() {
        return $("#dropdown option[value='" + self.dropdownValue() + "']").text();
    });
};

ko.applyBindings(new ViewModel());

Live example: http://jsfiddle.net/5PkBF/

If you were looking to do this in multiple places, it'd probably be best to write a custom binding, e.g.:

HTML

<div data-bind="text: dropdownValue"></div>
<select data-bind="selectedText: dropdownValue">
  <option value="1">Value1</option>
  <option value="2">Value2</option>
</select>

JS

ko.bindingHandlers.selectedText = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        value($("option:selected", element).text());

        $(element).change(function() {
            value($("option:selected", this).text());
        });
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $("option", element).filter(function(i, el) { return $(el).text() === value; }).prop("selected", "selected");
    }
};

function ViewModel() {
    this.dropdownValue = ko.observable();
};

ko.applyBindings(new ViewModel());

Live example: http://jsfiddle.net/5PkBF/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...