Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 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 Reply

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...