I'm having hard time getting the selected value of dropdown list using Knockout JS
jsFiddle
HTML
<select id="l" data-bind="options: locations, value=selectedLocation"></select>
<select id="j" data-bind="options: jobTypes, value=selectedJobType"></select>
<button data-bind="click: myFunction"> Display </button>
Script
var viewModel = {
locations: ko.observableArray(['All Locations', 'Sydney', 'Melbourne', 'Brisbane', 'Darwin', 'Perth', 'Adelaide']),
selectedLocation: ko.observable(),
jobTypes: ko.observableArray(['All Vacancies', 'Administration', 'Engineering', 'Legal', 'Sales', 'Accounting']),
selectedJobType: ko.observable(),
myFunction: function() {
alert(selectedJobType + ' ' +selectedLocation );
}
};
// ... then later ...
//viewModel.availableCountries.push('China');
// Adds another option
ko.applyBindings(viewModel);
That should be
value:selectedLocation
and:
value:selectedJobType
in you bindings. Bindings use the same syntax as an object literal.
Also, in your alert, you need viewModel.selectedJobType(), because (a) it's a property of viewModel not of global and (b) it's an observable so you need to call it to get the value. Same for selectedLocation.
Here's a working fiddle
Related
I am trying to access the option elements from a select2 dropdown list using a Knockout custom binding in order to disable some of them (some of the options). The custom binding is:
ko.bindingHandlers.select2 = {
after: ["options", "value"],
update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
var select2 = $(el).data("select2");
}
};
and the HTML part is:
<div style="width: 350px;">
<select style="width: 100%;" data-bind="value: attributiSelezionati, options: data, valueAllowUnset: true, optionsText: 'text', optionsValue: 'id', select2: { placeholder: 'Select an option...', allowClear: true, multiple: true}"></select>
</div>
where the data array is:
this.data = ko.observableArray([]);
this.data.push(new Item(1, "Item 1"));
this.data.push(new Item(2, "Item 2"));
this.data.push(new Item(2, "Item 22"));
this.data.push(new Item(3, "Item 3"));
this.data.push(new Item(null, "Item 4"));
class Item {
id: KnockoutObservable<number> = ko.observable<number>();
text: KnockoutObservable<string> = ko.observable<string>();
constructor(Id: number, Text: string) {
this.id(Id);
this.text(Text);
}
}
I can see the data when I hover over the el element but I do not know how to access it programmatically. Does anyone know how to get these items?
It should be in valueAccessor()
valueAccessor: This represents a JavaScript function that can be used to access the current property or expression involved in this binding. Because Knockout allows you to use either a view model property directly (such as "data-bind='enabled: isEnabled'"), or an expression (such as "data-bind='enabled: firstName.length > 0'"), there's a utility function that will "unwrap" and give you the actual value used in the binding. Incidentally, this function is called "ko.unwrap."
var val = ko.unwrap(valueAccessor());
//val.options;
I have a problem how to call onchanges knock js to my select option, i already have a function and html, but when i choose the select option, nothing changes
<select data-bind="event:{change:setSelectedStation() },
options: seedData,
optionsText: 'text',
optionsValue: 'value'">
</select>
here is my function
setSelectedStation: function(element, KioskId){
this.getPopUp().closeModal();
$('.selected-station').html(element);
$('[name="popstation_detail"]').val(element);
$('[name="popstation_address"]').val(KioskId);
$('[name="popstation_text"]').val(element);
// console.log($('[name="popstation_text"]').val());
this.isSelectedStationVisible(true);
},
Use knockout's two-way data-binds instead of manually subscribing to UI events.
Knockout's value data-bind listens to UI changes and automatically keeps track of the latest value for you.
Instead of replacing HTML via jQuery methods, you use text, attr and other value bindings to update the UI whenever your selection changes.
If you want to perform additional work when a selection changes (e.g. closing a pop up), you subscribe to the selected value.
var VM = function() {
this.seedData = [
{
text: "Item 1",
data: "Some other stuff"
},
{
text: "Item 2",
data: "Something else"
},
{
text: "Item 3",
data: "Another thing"
}
];
this.selectedItem = ko.observable();
this.selectedItem.subscribe(function(latest) {
console.log("Input changed");
}, this);
};
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="
value: selectedItem,
options: seedData,
optionsText: 'text'">
</select>
<!-- ko with: selectedItem -->
<p>
Your selection: <span data-bind="text: data"></span>
</p>
<!-- /ko -->
I am trying to get the text of selected index in dropdown using knockout.js,
following is my HTML
<select name="" id="management" class="form-control" data-bind="value: ManagementCompanies,optionText:ManagementCompaniestxt">
<option value="0">---Select---</option>
<option value="1">abcd</option>
<option value="2">efgh</option>
</select>
following is my Model binding:
var FilterViewModel = {
ManagementCompanies: ko.observable(''),
ManagementCompaniestxt:ko.observable('')
}
FilterViewModel.ManagementCompanies.subscribe(function (newValue) {
alert(FilterViewModel.ManagementCompaniestxt());
});
ko.applyBindings(FilterViewModel, window.document.getElementById("SelectFilters"));
i have tried to bind using Text as well but didn't work.
how can i get selected text abcd in subscribe event?
thanks
It's a bit weird that you're trying to get data from your view to your viewmodel. Usually, your view is a representation of your viewmodel. It's better to have the data needed to render your <select> in your model, and use knockout's options data-bind to render it.
Here's how you can do this:
var FilterViewModel = {
ManagementCompanies: ko.observable(''),
ManagementCompaniestxt: ko.observable(''),
options: [
{ text: "---Select---", value: 0 },
{ text: "abcd", value: 1 },
{ text: "efgh", value: 2 }]
}
FilterViewModel.ManagementCompanies.subscribe(function(newValue) {
console.log(newValue.text);
});
ko.applyBindings(FilterViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="value: ManagementCompanies,
options:options,
optionsText: 'text'">
</select>
I use a knockoutjs with templating plugin (Using Underscore Template with Knockout using interpolate due to asp.net)
If i have a header and a list:
<ul data-bind="template: { name: 'people' }"></ul>
<script type="text/html" id="people">
<h2>{{= hdr}}</h2>
{{ _.each(people(), function(item) { }}
<li>{{=item.name }} ({{=item.age }})</li>
{{ }); }}
</script>
also a button
<button id="bindclick">Click</button>
and a ja code where i use knockout:
ko.applyBindings({
hdr: "People",
people: ko.observableArray([{name:"name1",age: 45},{name:"name2",age: 33}])
});
How to do, that template value can be change with clicking a button instead of "Uncaught Error: You cannot apply bindings multiple times to the same element."?:
$("#bindclick").click(function() {
ko.applyBindings({
hdr: "People2",
people: ko.observableArray([{name:"name1",age: 45}])
});
});
Thanks
You should only need to call applyBindings once with a model object.
Later on in your click handler, you would simply update your model.
For example:
var theModel = {
hdr: ko.observable('People'),
people: ko.observableArray([{name:"name1",age: 45},{name:"name2",age: 33}])
};
ko.applyBindings(theModel);
$('#bindclick').click(function () {
theModel.hdr('People2');
theModel.people([{name:"name1",age: 45}]);
});
Updating the model should update your previously bound content.
I have this simple knockout.js application:
View:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>
and this simple ViewModel:
function documentType(id, name){
this.id = id;
this.name = name;
}
var viewModel = {
allDocumentTypes: ko.observableArray([]),
selectedDocument: ko.observable(''),
cl: function(){
viewModel.selectedDocument('');
}
};
/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);
I would expect, that after i click on span "CLEAR VALUE!", in select will be selected option "choose...", but it is not happening.
The value in viewModel is set to "" (empty string), which is right, but user still see old value in select.
Is there any way to do that?
Thanks for helping:)
You must change binding type to "value" instead of "selectedOptions". Next step is to set viewModel.selectedDocument in cl function:
viewModel.selectedDocument(null);
In some cases setting the observable value to null will not work, for example :
// This is the array
self.timePeriods = ko.observableArray([
new timePeriod("weekly", 7),
new timePeriod("fortnightly", 14),
new timePeriod("monthly", 30),
new timePeriod("half yearly", 180),
new timePeriod("yearly", 365)
]);
And below is the HTML part:
<select data-bind="options: timePeriods,
optionsText: function(item) {
return item.Name;
},
value: selectedPeriod"
class="combo">
You can't reset select box by:
self.selectedPeriod(null); // but this will not work
Insetead write this:
self.selectedPeriod(self.timePeriods()[0]);
<script>
var vm ={
CountryId=ko.observable(),
QC=ko.observable(),
clearSelectedStation: function () {
this.CountryId(null); //DropDown
this.QC(''); //Textbox
}
};
</script>
here is a html
<input type="text" tabindex="10" data-bind="value:QC"/>
<select class="dropdownlist" data-bind="options:Countries, value: CountryId,
optionsCaption: '--Select--', optionsText: 'CountryName', optionsValue: 'CountryId'">