knockout bind text label to dropdown value selected option text

knockout bind text label to dropdown value selected option text

Asked on December 27, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

    Try this method for binding to the new value :

    Just changing the values in the value attributes will work for this case :

    See this code which is using the jquery .

        In the 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>
    

        In the 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());
    

    See this working fiddle : http://jsfiddle.net/5PkBF/

        Built  a custom binding is best for creating the multiple classes , 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());
    
    Answered on December 27, 2018.
    Add Comment

        The ‘dropDownValue‘ is refers to the defined observable in the model , which is actually an observable array .

        See this HTML code :

    <span data-bind="text: dropDownValue"></span>
    <select data-bind="options: dropDownValues, optionsValue: 'FieldText', optionsText: 'FieldText', value: dropDownValue"></select>
    

        The same field is used for both the  optionValues and optionsText . In some  app ‘dropDownValue‘ was pre-populated in other places , so during opened a dialog box with the above select in it Make this as default to the previously populated value , and also bind it so that if the user changed it ,The same will reflect that change back in the database.

    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.