Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js - Get text selected value in a drop-down menu

I would like to know how to get the value of the TEXT selected from the dropdown menu, just remember that my drop down menu has the fixed data and are not populated by a "ko.observableArray ()". Any ideas?

When I select an option want to have: Value and Text selection.

<p>
    Select a car:
    <select data-bind="value: selectedValue, optionsText:???">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
</p>

<span data-bind="text: selectedValue"></span>
<br/>
<span data-bind="text: selectedText"></span>

My ko ViewModel:

var viewModel = {
      selectedValue : ko.observable(),
      selectedText :  ko.observable()
};

ko.applyBindings(viewModel);

See this Fiddle: JSFiddle

like image 501
Igor Avatar asked Dec 02 '14 18:12

Igor


People also ask

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How can I get the selected value of a drop down list with jQuery?

Use the jQuery: selected selector in combination with val () method to find the selected option value in a drop-down list.

How select a value in an option JavaScript?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

What is two way binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.


3 Answers

I dont know if there is a possible solution with Knockout.js. I let you two possible solutions:

Solution 1

You can use a bit of native Javascript to achieve your goal:

viewModel.selectedValue = ko.observable();
viewModel.selectedText = ko.computed(function () {
    var elem = document.querySelector("select option[value=" + viewModel.selectedValue() + "]");
    return elem && elem.innerHTML;
});

As you see, you can take the "value" and use it to return the DOM element that meets your requirements. Of course you can replace select with an id, if you need it.

Check this fiddle to see it working.

Solution 2

The Knockout way of doing this is having an array with all elements to be populated:

var cars = [{ id: 'volvo', name: 'Volvo' }, { id: 'saab', name: 'Saab' }, { id: 'mercedes', name: 'Mercedes' }, { id: 'audi', name: 'Audi' }];

After that, it depends on what you need when you say "value", remember that you are binding an object, not a key/value list:

HTML:

<select data-bind="options: cars, value: selectedCar, optionsText: 'name'"></select>

And your JS:

selectedCar = ko.observable();
selectedValue = ko.computed(function () { 
    return selectedCar() && selectedCar().id; 
});
selectedText =  ko.computed(function () { 
    return selectedCar() && selectedCar().name; 
});

This way you will have separately your "value" and your "text" (better called id and name properties) into two computed observables.

See the fiddle working.

like image 72
lante Avatar answered Oct 23 '22 01:10

lante


I have just had to acheive this and I have added a ko.computed function to retrieve the selected text from the options as below:

// assume that options has been populated with Key / Value pairs
self.options = ko.observableArray([]);

self.selectedType = ko.observable(null);
self.selectedTypeText = ko.observable(null);
self.selectedType.subscribe(function (newValue) {
    if (newValue) {
        self.checkAccess(newValue);

        $.each(self.options(), function (i, item) {
            if (item.Key === newValue) {
                self.selectedTypeText(item.Value);
            }
        });
    }
});
like image 38
csharpsql Avatar answered Oct 23 '22 00:10

csharpsql


You have to work with options binding for this. And like Jeff says, don't misuse.

var viewModel = {
      selectedValue : ko.observable(),
      selectedText :  ko.observable(),
    carOptions : ['Volvo','Saab', 'Mercedes', 'Audi']
};

ko.applyBindings(viewModel);

Markup:

<p>
    Selecte a car:
    <select data-bind="value: selectedValue, options: carOptions">

    </select>
</p>

<span data-bind="text: selectedValue"></span>
<br/>
<span data-bind="text: selectedText"></span>

This is the simplest way to do so. For more complicated scenarios visit the docs.

JsFiddle 1, JsFiddle 2

like image 2
deostroll Avatar answered Oct 23 '22 01:10

deostroll