Reputation: 2749
Using knockoutJs I have a simple select on a page
<select id="voucherCountry" data-bind="options: availableCountries, optionsValue:'isoId', optionsText: 'country', value:selectedCountry"></select>
In the view model I have
function searchViewModel()
{
var self = this;
self.voucherNumber = ko.observable();
self.selectedCountry = ko.observable();
self.availableCountries = ko.observableArray(
[
new Country(250, 'France'),
new Country(276, 'Germany'),
new Country(724, 'Spain'),
new Country(380, 'Italy'),
new Country(826, 'United Kingdom')
])
and
function Country(iso, name)
{
this.isoId = iso;
this.country = name;
}
On the HTML page I want to be able to change the value of the drop-down and have the drop-down list show the new opton and have selectedCountry update in teh view model.
So I tried a simple jQuery statement
function changeCountry(isoId)
{
$(voucherCountry).val(isoId);
}
which is called like so
changeCountry(380);
When I call this the text on the dropdown doesn't change, but when I click it to change the option the option I wanted to change it to is highlighted.
When I view what is helping the selectedCountry() variable it is set to the initial value, not the changed one.
So it seems it is updating the UI but not the view model.
I'm pretty sure there should be a simple solution to this, but I'm not getting it
UPDATE:
Okay so now I have a button
<button type="button" data-theme="b" data-bind="click: scanBarcode">Scan Barcode</button>
and in the view model this function:
self.scanBarcode = function()
{
self.selectedCountry(380);
}
selectedCountry is being updated but the UI is not.
I assume there is an issue with how I am using the optionsValue and value attributes in the <select>
data-bind?
Upvotes: 0
Views: 2225
Reputation: 5147
Your changeCountry method should be changing the value of the underlying observable that you have bound the select to:
function changeCountry(isoId)
{
selectedCountry(isoId);
}
That should then update both, as far as I'm aware.
You will also need to pass the new id in as a string, as knockout may well be using the type equality comparer (===), and the value in the html will be a string.
Upvotes: 2
Reputation: 7432
This block
function changeCountry(isoId)
{
$(voucherCountry).val(isoId);
}
Has multiple possible issues.
First, $(voucherCountry)
probably doesn't evaluate to a valid selector; if you want to select the dropdown by id you'll need to do this: $("#voucherCountry")
.
Then you can use $("#voucherCountry").val(123)
.
The second thing that could be mixing things up is that you're modifying the UI as a way of indirectly modifying your viewmodel - you're probably better off updating your VM directly, as in searchViewModel.selectedCountry(123)
Upvotes: 1