knockout bind text label to dropdown value selected option text

后端 未结 2 1308
梦谈多话
梦谈多话 2020-12-09 20:14

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?

2条回答
  •  离开以前
    2020-12-09 20:24

    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

    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

    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/

提交回复
热议问题