The issue is that when I bind options to the dropdown, "ui dropdown" makes it disappear and nothing is in the cell in my browser(it dosent use the css properly in jsfiddle). If i remove that css then i see the out of the box dropdown.
creating a table with a viewmodel collection and want a dropdown of values for the individual risks
//part of the viewmodel
var ViewModel = {
Collection: ko.observableArray(),
availableRisks: ['L', 'H'],
using
$('.ui.dropdown').dropdown();
doesn't help.
Sample code that dosent work with the dropdown:
http://jsfiddle.net/7vh2t33m/2/
There are bindings for jQuery UI and knockout, use them. http://gvas.github.io/knockout-jqueryui/
Rule of thumb, in a knockout application nothing may touch the DOM except knockout, or without informing knockout. Therefore, mixing knockout with jQuery UI without anything that bridges the gap between them will not work.
Taken from the example in knockout-jqueryUI selectmenu binding documentation:
var ViewModel = function () {
this.items = ko.observableArray([
{ id: '1', text: 'First' },
{ id: '2', text: 'Second' },
{ id: '3', text: 'Third' },
{ id: '4', text: 'Fourth' }
]);
this.value = ko.observable('1');
};
ko.applyBindings(new ViewModel());
and in the view
<!-- ko foreach: items -->
<input type="radio" name="radios" data-bind="attr: { value: id }, checked: $parent.value" />
<!-- /ko -->
<br/>
<select data-bind="value: value, selectmenu: { width: 300 }, options: items, optionsValue: 'id', optionsText: 'text'">
</select>
<br />
Related
I am trying to bind the dropdown . following code works
<select data-bind="options :MyArray"/>
However it doesn't works but when i add the Knockout bindings (as below) .the dropdown doesn't shows up
<select data-bind="options: MyArray, event:{change:DropdownChnaged.bind($data,'Task')} "/>
It looks as though you have a typo in your change event (DropdownChnaged -> DropdownChanged). That maybe the root cause of the issue.
But I would also avoid using the change event and instead use knockouts subscriber functionality.
When the dropdown value is being set, you can subscribe to the value and execute a function when the observable value is updated. I have provided a snippet below which should demonstrate how you can use this.
var VM = function() {
this.MyArray = [
{
text: "Item A",
data: "This is the description for Item A",
otherData: { myData: 'MyOtherDataA'}
},
{
text: "Item B",
data: "Description of Item B",
otherData: { myData: 'MyOtherDataB'}
},
{
text: "Item C",
data: "This is Item C's description",
otherData: { myData: 'MyOtherDataC'}
}
];
this.selectedItem = ko.observable();
this.selectedItem.subscribe(function(latest)
{
console.log("Change event triggered");
console.log(latest);
}, 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: MyArray, optionsText: 'text'">
</select>
<!-- ko with: selectedItem -->
<p>
Item Description: <span data-bind="text: data"></span>
</p>
<!-- /ko -->
I am new to knockoutJs, as i am trying to display the selected values by binding. But am facing issues with duplicate values.
For example:
As per the below example snippet, If i select one from the dropdown, the binding result is displaying name "one" as selected, this is correct.
{name:"one",price:32.50}, {name:"two",price:32.50},
After that if I select other option from drop down i.e name two, the binding result is not displaying name two as selected, instead it is keep displaying the name="one" only, which is in-correct.
Observation: I see that this is happening due to the same price set for all the option values, if I update them with different prices the options values are binding properly.
Here my confusion is that why the binding logic is not applying properly when the price value is same but the name is different.
I am trying to achieve this by below code.
Html
<select data-bind="options: beforeEventPedersensDropoffCustomerLocation,optionsCaption: 'Please Choose Closest Location',
optionsText: 'name', optionsValue: 'price', value: selectedPricebepdcl" id="before_event_pedersens_dropoff_customer_location_time" ></select>
Js
self.beforeEventPedersensDropoffCustomerLocation = [
{name:"one",price:32.50},
{name:"two",price:32.50},
{name:"three",price:32.50},
{name:"four",price:32.50},
{name:"five",price:32.50},
{name:"six",price:32.50},
{name:"seven",price:0}
];
self.selectedPricebepdcl = ko.observable("");
console.log()
self.beforeEventVal = ko.computed(function() {
if(self.selectedPricebepdcl() !== "")
return ko.utils.arrayFirst(self.beforeEventPedersensDropoffCustomerLocation, function(time) {
return self.selectedPricebepdcl() === time.price;
});
return null;
}, this);
Result
<p data-bind="with: beforeEventVal">
<span data-bind="text: name"></span>
</p>
<p data-bind="with: beforeEventVal">
<span data-bind="text: price"></span>
</p>
Can anyone help me on this.
The problem is that you have set optionsValue: 'price', so the only information you have about which item is selected is the price. Then you try to use that to find the selected item from among the available items, but you cannot do that because it is not a unique identifier.
Instead, if you don't specify optionsValue, Knockout will use the entire item as the value of the select. That also lets you do away with looking up the selected value, because you have the selected value.
function VM() {
self = this;
self.beforeEventPedersensDropoffCustomerLocation = [{
name: "one",
price: 32.50
},
{
name: "two",
price: 32.50
},
{
name: "three",
price: 32.50
},
{
name: "four",
price: 32.50
},
{
name: "five",
price: 32.50
},
{
name: "six",
price: 32.50
},
{
name: "seven",
price: 0
}
];
self.selectedBepdcl = ko.observable("");
self.selectedName = ko.pureComputed(() => {
const sb = self.selectedBepdcl();
return sb && sb.name ? sb.name : '';
});
}
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: beforeEventPedersensDropoffCustomerLocation,
optionsCaption: 'Please Choose Closest Location',
optionsText: 'name',
value: selectedBepdcl" id="before_event_pedersens_dropoff_customer_location_time">
</select>
<p data-bind="with: selectedBepdcl">
<span data-bind="text: name"></span>
</p>
<p data-bind="with: selectedBepdcl">
<span data-bind="text: price"></span>
</p>
Pretend this is hidden:
<input data-bind="value: selectedName">
I have the following binding in js fiddle.
<div class="container body-content">
<div>Name : <span data-bind="text: Name"></span>
</div>The select control should be below
<select multiple data-bind="selectPicker: teamID, optionsText: 'text', optionsValue : 'id', selectPickerOptions: { optionsArray: teamItems, disabledOption: IsDisabled }"></select>
<div>Selected Value(s)
<div data-bind="text: teamID"></div>
</div>
</div>
I am thinking of doing this disabledOption: IsDisabled and then adding
this.teamItems = ko.observableArray([{
text: 'Chris',
id: 1,
IsDisabled: false
}, {
text: 'Peter',
id: 2,
IsDisabled: false
}, {
text: 'John',
id: 3,
IsDisabled: false
}]);
I would like to know how to disable an option in the select.
In the knockout docs, there's an example that shows how you can disable an item using an optionsAfterRender method.
About the method you can pass to it:
It has to be in your viewmodel, not in your items
It takes in the option HTML node, and the item it's bound to
So step one is to find a place to store which items are disabled. The easiest option would be to store it inside your teamItems' objects:
{
text: 'Chris',
id: 1,
disable: ko.observable(true)
}
Now, we need to add a method that takes in an item and creates a binding. We can take this straight from the example:
this.setOptionDisable = function(option, item) {
ko.applyBindingsToNode(option, {
disable: item.disable
}, item);
}
Finally, we need to tell knockout to call this method:
<select multiple data-bind="optionsAfterRender: setOptionDisable, ...
Note that after changing a disable property in one of your items, you'll have to call teamItems.valueHasMutated manually.
Here's an updated fiddle:
http://jsfiddle.net/nq56p9fz/
I have two select dropdowns, the first being the parent of the second. I am able to successfully bind the parent select back to a 'selected item'. But I am unable to bind the child select using ng-model back to the selected parent. I couldn't quite get my example working as I am new to angular but hopefully you get the picture.
$scope.model = {};
$scope.model = {
categories: [{
id: 1,
name: 'Ford',
subCategory: ['focus', 'ranger', 'F150'],
filterValue: ''
}, {
id: 2,
name: 'Honda',
subCategory: ['accord', 'civic', 'pilot'],
filterValue: ''
}],
selectedCategory: {}
}
$scope.categoryChange = function() {
console.dir($scope.selectedCategory);
}
$scope.subCategoryChange = function() {
console.dir($scope.selectedCategory.subCategory);
}
var init = function() {
$scope.model.selectedCategory = $scope.model.categories[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<select ng-model="model.selectedCategory" ng-options="category as category.name for category in model.categories" data-ng-change="categoryChange()"></select>
<select ng-model="model.selectedCategory.filterValue" data-ng-options="subCategory for subCategory in model.selectedCategory.subCategory" data-ng-change="subCategoryChange()"></select>
For me it's working!
Maybe you forgot to put ng-app & ng-controller
See This --> Sample
Scenario: I make a request to the server for a part. It gives me this back (it's pseudo, but represents what I'm looking at):
{
PartNumber : "XYZ",
Description: "ABCFOO",
ProductClass: "Widget",
FieldList:[
{Name: "PROGRAM TYPE", Value: "Program3"},
{Name: "SHIP", Value: false},
{Name: "NOTES", Value: "SomeValue1"}
],
MoreStuff : [{
...
}]
}
Note the FieldList list of elements, that's the focus here.
The server also gave me a list of certain fields, their types and default values. It looks like this:
[
{FieldName : "PROGRAM TYPE", FieldType: "List", Defaults: [{Name:"Program 1", Value: "Program1"},{Name:"Program 2", Value: "Program2"},{Name:"Program 3", Value: "Program3"}]},
{FieldName : "SHIP", FieldType : "Boolean", Defaults: []},
{FieldName : "NOTES", FieldType: "TextArea", Defaults: []}
]
That comes in a seperate REST call, and the prior to loading my Part. I use it to create part of the HTML page for the Part. You can see they're similarly related to the FieldList section from when I ask for Part.
From that "list of fields" and defaults -- I generate the appropriate HTML elements on the page. If it's a Boolean field type, I create a checkbox - if it's a list, I create a SELECT (with options given in Defaults), TextArea is a text-area, etc. That all works fine. It ends up looking like:
<input data-bind="textInput: PartNumber"/>
<textarea data-bind="textInput: Description"></textarea>
<!-- generating fieldlist - i create a pseudo attr because the field name can have spaces-->
<select field_label="PROGRAM TYPE"> <!-- how the heck do i bind to this??-->
<option value="Program1">Program 1</option>
<option value="Program2">Program 2</option>
<option value="Program3">Program 3</option>
</select >
<input type="checkbox" field_label="SHIP" value="true"/> <!-- or this, how to bind to it?!-->
<!-- end of field list generation -->
Now I take the object (the part I'm given) and put that into my ViewModel - that is all working just swimmingly. I make it easy and just use ko.mapping.fromJS(rest_data); Works just fine.
Data binding is ducky -- for what I am able to bind it to. My issue comes from -- how the heck do I map my FieldList to the HTML I generated for the fields the server gave me?. My data / my viewmodel object has FieldList in it, with a buncha stuff I want to map to that generated stuff. The only real "key" I have is the self-created field_label I have, because the server's FieldName can have spaces.
So I guess what I'm asking is, I have that array of FieldList from my part. I have the whole Part object in my view model and it's all fine. How do I take that FieldList and map it into my self-generated set of fields from the other object (ie., take the FieldList name and tie it to the element with field_label of the same value?)
Spelled out - it'd be like: How to map FieldList with Name of "PROGRAM TYPE" to HTML element having field_label of "PROGRAM TYPE".
I begin to think something like this might be the direction I should be going:
http://jsfiddle.net/MhdZp/128/
but it goes over my head.
One way to approach this:
function Option(definition) {
this.definition = definition;
this.value = ko.observable();
this.templateName = 'input-template-' + definition.FieldType;
}
function ViewModel() {
var self = this;
// from REST call
var fieldDefinition = [{
FieldName: "PROGRAM TYPE",
FieldType: "List",
Defaults: [
{ Name: "Program 1", Value: "Program1" },
{ Name: "Program 2", Value: "Program2" },
{ Name: "Program 3", Value: "Program3" }
]
}];
self.options = ko.observableArray();
// for the sake of the example
self.options.push(new Option(fieldDefinition[0]));
// methods
self.optionByName = function (name) {
return ko.utils.arrayFirst(self.options(), function (option) {
return option.Name = name;
});
};
// poor man's init, imagine 2nd rest call instead
self.optionByName("PROGRAM TYPE").value("Program3");
}
and
<script type="text/html" id="input-template-List">
<label data-bind="text: definition.FieldName"></label>
<select data-bind="
value: value,
options: definition.Defaults,
optionsText: 'Name',
optionsValue: 'Value',
optionsCaption: 'Please select...'
"></select>
</script>
and
<div data-bind="foreach: options">
<div data-bind="template: templateName"></div>
</div>
Add more templates as needed, this should be very easy to extend.
jsFiddle: http://jsfiddle.net/0nxt2zte/