save data in knockout.js - javascript

Help me please with knockout.js problem:
Why variable currentObject is undefinded ? How I can save current selected object in some variable ?
I have follow html view for down drop list:
<select data-placeholder="Select object" class="span5" id="objects" data-bind="options: objects, optionsText: 'Name', optionsValue: 'Id', value: currentObject">
<option></option>
</select>
ModelView:
function baseViewModel() {
self.objects = ko.observableArray([]);
...
self.currentObject = ko.observable();
...
self.func = function() {
//allert(self.objects()[0].Name) //return correct Name
alert(self.currentObject().Name) //returns undefinded
}
}

In your data-bind, you have value: currentObject which will indeed do a two-way bind between currentObject and the select's value.
The select's value is set to the Id field of the selected option's object (because of optionsValue: 'Id' in your data-bind).
So, currentObject will be set to the Id field of the selected object, and that's why doing .Name gets you undefined.
I suggest not using optionsValue at all, this way KO will handle the value and it will be as if the value of the selectbox is the actual selected object, and value: currentObject will correctly set currentObject to the selected object. (And if you do want to use optionsValue, then know that currentObject will be set to the object's field, not the object itself)
Fiddle: http://jsfiddle.net/antishok/KXhem/78/

Related

Knockout: Iterate over object and show value in dropdown

I need some help with js/knockout/databindings.
In my code I am receiving an object like this:
Received object
I wish to show the value in a dropdown, and the key should be stored as the value.
I tried using some knockout data-bind like this:
<select id="routeTable" class="form-control" data-bind="
options: availableRouteTables,
optionsText: availableRouteTables.key,
optionsValue: availableRouteTables.value,
value: selectedRouteTable,
optionsCaption: '- velg rutetabell -'"></select>
I know that "availableRouteTables.key" and "availableRouteTables.value" are wrong, but it was just to explain/show what I want.
As of now the object only looks like this in JS:
this.availableRouteTables = availableRouteTables;
In the dropdown it is shown like this:
Dropdown failure
Can someone help me with identifying the issue and fix it?
thanks a lot!
When you receive the data you have to change it's structure to work with the options binding:
// Convert to array of objects with value and text properties
var availableRouteOptions = [];
for(var key in availableRouteTables) {
availableRouteOptions.push({
value: key,
text: availableRouteTables[key]
});
}
And you have to change your bindings:
options: availableRouteOptions,
optionsText: 'text',
optionsValue: 'value',

Knockout.js - select value not set

I am using knockout.js, and it's not setting the value of an empty option (Four):
<select data-bind="value: item.widgetValue, attr: {id: item.widgetName, name: item.widgetName}, options: item.options, optionsText: ‘label’, optionsValue: ‘value’” id=”fld-“ name=”fld0”>
<option value=”one”>One</option>
<option value=”two”>Two</option>
<option value=”three”>Three</option>
<option value>Four</option>
...
</select>
This is creating a problem: when you're on any option and try to select Four, it selects One; it will only select Four the second time you try to select it.
I have tried changing the knockout data-bind to fix it:
value: $.trim(item.widgetValue)
This allows you to select Four immediately, but incorrectly shows One as being selected after you submit the form with Four selected.
Any ideas as to what could be causing this, or how to fix it?
You shouldn't be manually setting options if you are using the options binding on your select element. If those are being dynamically created by the binding (ie. you are actually using item.options for your source) then check the objects you are binding the select element to -
item.options probably looks like this (missing a value or is somehow not like the other options) -
item.options = [
{ label: 'someLabel1', value: 'someValue1' },
{ label: 'someLabel2', value: 'someValue2' },
{ label: 'someLabel3', 'someValue3' }
];
but should be a more uniform object like this (well defined model) -
function optionModel(label, value) {
var self = this;
self.label = ko.observable(label);
self.value = ko.observable(value);
}
item.options = [
new optionModel('someLabel1', 'someValue1'),
new optionModel('someLabel2', 'someValue2'),
new optionModel('someLabel3', 'someValue3')
];

Knockout select and textbox sharing binding

I have a page with a select and an input-box being bound to the same value. The idea is that normally one would select a value from the select, however, the user should also be able to enter an arbitrary string in the input-box. The problem is that if I enter something not present in the select, because of the binding, the value is set to the first item in the select.
This is the behavior I want to achieve:
User selects value from select
Value is set to selected item.
Input is updated with selected value.
User enters text in input
Value is set to entered text.
Select does not change unless Value is present in the collection of available values.
In other words, what I want is for the last changed control to be the valid Value. But I also want both controls to be up to date as long as a given value is valid for that control.
My code looks like this:
js
var viewModel = { Value: ko.observable('1'), Set: ['1', '2', '3'] };
ko.applyBindings(viewModel);
html
<!-- ko if: Set.length > 1 || (Set.length > 0 && Set[0] != '') -->
<select type="text" class="form-control input-small" data-bind="options: Set, value: Value">
</select>
<!-- /ko -->
<input class="form-control input-small" data-bind="value: Value" style="margin-top: 5px;" />
Here is a jsfiddle showing how the code currently works: http://jsfiddle.net/b2RwG/
[Edit]
I've found a working solution (http://jsfiddle.net/b2RwG/2/), however it's really not pretty, and there has to be a better way to solve this problem.
As you can see I add an inputValue observable that is bound to the text input.
I also add an computed named virtualSet that contains both original items and the new item (from the text input).
I susbcribe to the inputValue so the select will be automatically set when you are typing.
var viewModel = {
inputValue: ko.observable('1'),
Value: ko.observable('1'),
Set: ['1', '2', '3']
};
viewModel.virtualSet = ko.computed({
read: function () {
var vs = this.Set.slice(0);
if (this.inputValue() && this.inputValue().length)
vs.unshift(this.inputValue());
return vs;
},
owner: viewModel
});
viewModel.inputValue.subscribe(function (value) {
viewModel.Value(value);
});
See fiddle
I hope it helps.
You can have the select use a computed observable instead, which updates only if the value makes sense.
I made an example where i added a caption to the select. The result is that it doesn't automatically pick the first value, but instead tries to set undefined value, when it reads a value that isn't included in the Set array.
<select type="text" class="form-control input-small" data-bind="options: Set, value: SelectValue, optionsCaption: 'Other value'"></select>
To do that, a constructor function instead of an object literal will make it easier, because then you can access the Value observable through the self reference.
function ViewModel() {
var self=this;
this.Value = ko.observable('1');
this.Set = ['1', '2', '3'];
this.SelectValue= ko.computed({
read: function() {
var val = self.Value();
return val;
},
write: function(value) {
if(value) self.Value(value);
}
});
}
See http://jsfiddle.net/b2RwG/4/

Set initial dropdown value to viewmodel

I'm having some issues with a dropdown list where I need to pass the initial value to the viewmodel. Just to clarify: I'm working on an edit-form, so the dropdownlist will be populated with an already-selected value.
What I have so far is:
Razor:
<select data-bind="selectedOptions: selectedLength">
// razor code omitted
foreach(var preValue in lengthPreValues)
{
if(lengthPreValues.Contains(preValue.value))
{
<option selected="selected" value='#preValue'>#preValue</ option>
}
else
{
<option value='#preValue'>#preValue</option>
}
}
And my viewmodel looks like this:
var editOfferViewModel = {
// Properties omitted
selectedLength: ko.observable("")
};
ko.applyBindings(editOfferViewModel);
While this definately works when selecting a new value, I'm a bit stuck when it comes to setting the initial value. I was fortunate enough to get some great help from Ryan Niemeyer here on stackoverflow.com with checkboxes and creating custom bindinghandlers, but I'm still
having a hard time to figure it out to be honest.
So, any help and/or hint on this is greatly appreciated!
A common and easy way to do this is to serialize your model values to the page. This would be something like:
var viewModel = {
choices: ko.observableArray(#Html.Raw(Json.Encode(Options))),
selectedChoices: ko.observableArray(#Html.Raw(Json.Encode(SelectedOptions)))
};
Then, just use a standard data-bind on your select like:
data-bind="options: choices, selectedOptions: selectedChoices"
You then don't even need to populate the option elements in Razor.
If your viewModel is built in an external file, then you can just set the value of the observables in your view (after your external script has been loaded)
My data is something like :
dataList = [ {name:'length1',id:1},{name:'length2',id:2},{name:'length3',id:3},{name:'length4',id:4},{name:'length5',id:5} ]
And I have been using that data with dropdown like this :
<select name="xxx" id="xxxid" data-bind="options: dataList, value: selectedLength , optionsText: 'name', optionsValue: 'id', optionsCaption: 'Please Select...'"></select>
<select name="xxx2" id="xxxid2" data-bind="options: dataList, selectedOptions: multiSelectedLength , optionsText: 'name', optionsValue: 'id', optionsCaption: 'Please Select...'" size="5" multiple="true"></select>
var editOfferViewModel = {
selectedLength: ko.observable(),
multiSelectedLength: ko.observableArray()
};
ko.applyBindings(editOfferViewModel);
$(document).ready(function() {
// Set initial value
editOfferViewModel.selectedLength(2);
// Set inital multi value
editOfferViewModel.multiSelectedLength(['2','3']);
});
You can use value property to set initial value.
Here is the working example.

Binding initial/default value of dropdown (select) list

I'm having a small issue with setting the initial value of a dropdown. The code below is the view model definition and the initialization in $(document).ready. I have an array called sourceMaterialTypes and a selectedSourceMaterialType representing the selected value of that array. I am initializing the view model with values from the (ASP.Net MVC) Model and ViewBag.
var viewModel = {
sourceMaterialTypes :
ko.observableArray(#Html.Raw(Json.Encode(ViewBag.SourceMaterialTypes))),
selectedSourceMaterialType :
ko.observable(#Html.Raw(Json.Encode(Model.SourceMaterialType))),
ingredientTypes :
ko.observableArray(#Html.Raw(Json.Encode(ViewBag.IngredientTypes))),
selectedIngredientType : ko.observable()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
viewModel.selectedSourceMaterialType.subscribe(function(newSourceMaterialType) {
$.getJSON("/IngredientType/FindByMaterialType",
{ "id": newSourceMaterialType })
.success(function (data) {
viewModel.ingredientTypes($.parseJSON(data));
})
.error(function () { alert("error"); });
});
});
The following is the definition of my dropdown (select) list with the Knockout binding definition.
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType"></select>
This all works fine except for the initially selected value in the source materials dropdown (selectedSourceMaterialType is bound correctly so when the dropdown selection changes its value is correctly updated, it is only the initial selection I am having a problem with), which is always the first item in the sourceMaterialTypes array on my view model.
I would like the initially selected value to be that which is initialized from the (server-side) model as the value of selectedSourceMaterialType view model property.
I guess you need to pass the Id only and not the whole object in the selectedSourceMaterialType observable function ->
selectedSourceMaterialType: ko.observable(#Model.SourceMaterialType.Id)
The API has the solution for you, you'll just need to add optionsCaption to your select.
<select id="SourceMaterialTypeId"
name="SourceMaterialTypeId"
data-bind="options: sourceMaterialTypes,
optionsText: 'Name',
optionsValue : 'Id',
value: selectedSourceMaterialType,
optionsCaption: 'Please select...'"></select>
As #nEEBz suggested, selectedSourceMaterialType is initialized improperly. In the learn.knockoutjs.com "Lists and Collections" tutorial, they initialize their viewmodel's selected-item property by passing the value of a specific index of the observable array. For example, do this:
selectedSourceMaterialType: ko.observable(sourceMaterialTypes[2])
...instead of this:
selectedSourceMaterialType: ko.observable({"Id":1,"Name":"Coffee Bean" /* ... */});
That way, the value of the selected item is a reference to the item in the same observable array that the dropdownlist items come from.

Categories