JQuery timepicker in knockout list - javascript

Why TimePicker working well outside knockout list, but does not work in him. How to launch it in knockout list?
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<link href="~/Scripts/timepicker/bootstrap-datepicker.css" rel="stylesheet" />
<link href="~/Scripts/timepicker/jquery.timepicker.css" rel="stylesheet" />
<link href="~/Scripts/timepicker/site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/timepicker/bootstrap-datepicker.js"></script>
<script src="~/Scripts/timepicker/jquery.timepicker.min.js"></script>
<script src="~/Scripts/timepicker/site.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<div class="demo">
<h2>Basic Example</h2>
<p><input id="basicExample" type="text" class="time" /></p>
</div>
<table>
<thead>
<tr>
<th>Passenger name</th>
<th>Time</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td><input id="basicExample" type="text" class="time" data-bind="value: time"/></td>
</tr>
</tbody>
</table>
<script>
$('#basicExample').timepicker();
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items = [{ name: 'Jhon', time: '12:00' }, { name: 'Nick', time: '11:00' }];
}
ko.applyBindings(new MyViewModel());
</script>

When you use a foreach binding, Knockout is creating DOM elements for each of the items in your list. They are not there when you do you timepicker initialization.
(Also, you can't use the same ID twice in an HTML document. Your call will only find the first one.)
For any widget that needs to be initialized, you should have a custom binding handler. It might be as simple as this:
ko.bindingHandlers.timePicker = {
init: function (el) {
$(el).timepicker();
}
}
Then you would use that to bind it.
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td><input type="text" class="time" data-bind="timepicker: true, value: time"/></td>
</tr>
</tbody>
Probably there needs to be more done in the binding handler than that. Someone else wrote an example fiddle with their own timepicker binding handler.

The main problem you are facing here is that you are trying to define the JqueryUI TimePicker before you have defined your viewmodel and apply the bindings.
That means basically that your DOM nodes do not exist at this point.
To avoid that I would recommend you using the "afterRender(nodes, elements)" option in knockout foreach:
http://knockoutjs.com/documentation/foreach-binding.html
This way your DOM nodes will be there and so your inputs can be "transformed" into TimePickers
BTW, remove the "id" inside the KO foreach part, it´s useless (KO will generate another unique UI in each node)
Hope this helps

Related

Update Knockoutjs table

I have a table bound to knockoutjs using foreach.
<table>
<thead>
<tr>
<th>ID</th>
<th>BALANCE</th>
<th>GENDER</th>
<th>AGE</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: data -->
<tr>
<!-- ko foreach: Object.keys($data) -->
<td>
<label data-bind="text: $parent[$data]" />
</td>
<!-- /ko -->
</tr>
<!-- /ko -->
</tbody>
</table>
Table rows iterate an observableArray (about 2000 items).
After table is rendered, I need to edit a row but table do not render the row changed.
How can I do this whithout clear observableArray and reload it again?
Here JSFIDDLE
Thank you
You need to make your data array properties observable so knockout would observe the changes. I'd suggest you to use knockout mapping to do the job of creating observables for you, like this:
var foo = new MyVM();
var mapping = {
create: function(options) {
return ko.mapping.fromJS(options.data);
}
};
ko.mapping.fromJS(myJS, mapping, foo.data);
But you need to change your markup so it won't just iterate through object properties, but explicitly specify which property should be used:
<tbody>
<!-- ko foreach: data -->
<tr>
<td>
<label data-bind="text: _id" />
</td>
<td>
<label data-bind="text: balance" />
</td>
<td>
<label data-bind="text: gender" />
</td>
<td>
<label data-bind="text: age" />
</td>
</tr>
<!-- /ko -->
</tbody>
Here is working demo. Of course you can make observables yourself, then just rewrite your code, so every property of each item in data array would be an observable.
Edit:
Well, since we don't know the actual properties, I'd suggest the following code to make observables:
var foo = new MyVM();
for (var i=0, n = myJSON.length; i < n; i++) {
for (var prop in myJSON[i])
if (myJSON[i].hasOwnProperty(prop))
myJSON[i][prop] = ko.observable(myJSON[i][prop]);
}
foo.data(myJSON);
And in your view model function:
self.changeRow = function (){
if(typeof self.data() != "undefined"){
self.data()[0]["gender"]("male");
}
};
See updated demo.

Displaying contents of a knockout observable array

Hi guys I'm new to java Script knockout framework, I would like to display contents of an array using knockout, in reality I want to retrieve these contents from a database using ajax but I decided to start with something simpler, which is like this:
$(document).ready(function() {
function requestViewModel() {
this.branchName = ko.observable();
this.allItems = ko.observableArray({items:[{orderItemId:1,
description:"Chocolate",
unitCost:8.50,
quantity:10,
total:84.0},
{orderItemId:2,
description:"Milk",
unitCost:5.0,
quantity:10,
total:50.0},
{orderItemId:3,
description:"Sugar",
unitCost:10.0,
quantity:20,
total:200.0}]});
};
ko.applyBindings(new requestViewModel());
});
......and here is my HTML
Branch Name: <input type="text" name = "branchName">
<br><br><br><br>
<table>
<thead>
<tr><th>Item id</th><th>Description</th><th>Unit Cost</th><th>Quantity</th><th>Total</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: orderItemId"></td>
<td data-bind="text: description"></td>
<td data-bind="text: unitCost"></td>
<td data-bind="text: quantity"></td>
<td data-bind="text: total"></td>
</tr>
</tbody>
</table>
Please help where you can coz I get an error which is:
"Error: The argument passed when initializing an observable array must be an array, or null, or undefined."
The error says it all. You need to pass in an array instead of an object like so:
this.allItems = ko.observableArray([{orderItemId:1,
description:"Chocolate",
unitCost:8.50,
quantity:10,
total:84.0},
{orderItemId:2,
description:"Milk",
unitCost:5.0,
quantity:10,
total:50.0},
{orderItemId:3,
description:"Sugar",
unitCost:10.0,
quantity:20,
total:200.0}]);
Note the removal of {items: and }.

How to display only selected records in the result table

There are two tables using the same source. These tables are using source binding of kendo templates. At present the source for both these tables are employees. Both these tables are displaying the same data.
Now, we need to modify it to show only check-box selected records in the result table. Also, when user clicks on the delete button on the result table, the check-box should be un-selected in the section table.
What modification do we need to do to make it work in MVVM?
Head
<head>
<title>MVVM Test</title>
<script type="text/javascript" src="lib/kendo/js/jquery.min.js"></script>
<script type="text/javascript" src="lib/kendo/js/kendo.web.min.js"></script>
<!----Kendo Templates-->
<script id="row-template" type="text/x-kendo-template">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: age"></td>
<td><button type="button" data-bind="click: deleteEmployee">Delete</button></td>
</tr>
</script>
<script id="selection-table-template" type="text/x-kendo-template">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: age"></td>
<td>
<input type="checkbox" name="selection" value="a">
</td>
</tr>
</script>
<!--MVVM Wiring using Kendo Binding-->
<script type="text/javascript">
$(document).ready(function () {
kendo.bind($("body"), viewModel);
});
</script>
</head>
MVVM
<script type="text/javascript">
var viewModel = kendo.observable({
// model definition
employees: [
{ name: "Lijo", age: "28" },
{ name: "Binu", age: "33" },
{ name: "Kiran", age: "29" }
],
personName: "",
personAge: "",
//Note: Business functions does not access any DOM elements using jquery.
//They are referring only the objects in the view model.
//business functions (uses "this" keyword - e.g. this.get("employees"))
addEmployee: function () {
this.get("employees").push({
name: this.get("personName"),
age: this.get("personAge")
});
this.set("personName", "");
this.set("personAge", "");
},
deleteEmployee: function (e) {
//person object is created using "e"
var person = e.data;
var employees = this.get("employees");
var index = employees.indexOf(person);
employees.splice(index, 1);
}
});
</script>
Body
<body>
<table id="selectionTable">
<thead>
<tr>
<th>
Name
</th>
<th>
Age
</th>
</tr>
</thead>
<tbody data-template="selection-table-template" data-bind="source: employees">
</tbody>
</table>
<br />
<hr />
<table id="resultTable">
<thead>
<tr>
<th>
Name
</th>
<th>
Age
</th>
</tr>
</thead>
<!--The data-template attribute tells Kendo UI that the employees objects should be formatted using a Kendo UI template. -->
<tbody data-template="row-template" data-bind="source: employees">
</tbody>
</table>
</body>
REFERENCES
set method - ObservableObject - Kedo API Reference
set method - kendo Model - Kedo API Reference
Filtering source in a Kendo Template
Kendo-UI grid Set Value in grid with Javascript
First things first.
If you remove the object from the viewModel when you delete it, it will be removed from your source table as well. You would need two arrays to handle this if you wanted it to be the way you describe. But based on the first part of your question, I thought I would post a solution.
HTML
<script id="row-template" type="text/x-kendo-template">
<tr data-bind="visible: isChecked">
<td data-bind="text: name"></td>
<td data-bind="text: age"></td>
<td>
<button type="button" data-bind="click: deleteEmployee">Delete</button>
</td>
</tr>
</script>
<script id="selection-table-template" type="text/x-kendo-template">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: age"></td>
<td>
<input type="checkbox" name="selection" data-bind="checked: isChecked"/>
</td>
</tr>
</script>
<table id="selectionTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody data-template="selection-table-template" data-bind="source: employees"/>
</table>
<br />
<hr />
<table id="resultTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody data-template="row-template" data-bind="source: employees"/>
</table>
JAVASCRIPT
var viewModel = kendo.observable({
employees: [
{ name: "Lijo", age: "28", isChecked: true },
{ name: "Binu", age: "33", isChecked: true },
{ name: "Kiran", age: "29", isChecked: true }
],
personName: "",
personAge: "",
addEmployee: function () {
this.get("employees").push({
name: this.get("personName"),
age: this.get("personAge")
});
this.set("personName", "");
this.set("personAge", "");
},
deleteEmployee: function (e) {
var person = e.data;
var employees = this.get("employees");
var index = employees.indexOf(person);
var employee = employees[index];
//set
employee.set('isChecked', false);
}
});
$(document).ready(function () {
kendo.bind($("body"), viewModel);
});
JSFiddle
Fiddle
Summary
Use data-bind="visible: isChecked" in "row-template" to show only selected records in the bottom table.
Make template for checkbox as
<input type="checkbox" name="selection" data-bind="checked: isChecked"/>
In the delete function, use following
employee.set('isChecked', false);
Use a dictionary to store [employee, boolean] to store employee and the checkbox state, and bind the dictionary to the view
Check this

Build knockout model and view dynamically, radio buttons not being set

I am in the process of making one of my previous questions fully dynamic in that the model is built from server data, and the view loops through the viewmodel via the knockout ko foreach functionality.
The problems I am facing are:
The radio options don't stay with the value set, i.e. I click on the Operating System, and then select a Database option, and then the Operating System setting disappears.
The dependent options (in this case database and clustering) do not have their initial selection selected when the dependent option changes (i.e. when OS changes, DB should go back to the first option, none).
My fiddle is here and i think the problem is either related to the code below:
computedOptions.subscribe(function () {
var section = this;
console.log("my object: %o", section);
section.selection(section.options()[0].sku);
},section);
Or my view bindings:
<!-- ko foreach: selectedOptions -->
<h3><span data-bind="text: description"></span></h3>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th colspan="2" style="text-align: left;">Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: options -->
<tr>
<td><input type="radio" name="$parent.name" data-bind="checkedValue: $data, checked: $parent.selection" /></td>
<td style="text-align: left;"><span data-bind="text: name"></span></td>
<td style="text-align: left;"><span data-bind="text: price"></span></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<!-- /ko -->
I am not sure which and would appreciate a fresh eyes as my brain hurts from the jsfiddle session.
You have two problems:
You are not correctly binding your radio button's names: name="$parent.name" is not a knockout binding expression and it just assigns the string "$parent.name" to all of your radio buttons. What you need is to use the attr binding:
<input type="radio" data-bind="checkedValue: $data,
checked: $parent.selection,
attr: { name: $parent.name }" />
The initial selection is not working because you are using the checkedValue: $dataoption this means that your checked should contain the whole object and not just one property (sku) so you need to change your computedOptions.subscribe to:
computedOptions.subscribe(function () {
var section = this;
section.selection(section.options()[0]);
},section);
Demo JSFiddle.

How to render a table with some fixed and some dynamic columns

I want to get a table with these columns:
[Name]
[Club]
[Dynamic1]
[Dynamic2]
[Dynamic3]
etc etc.
I tried this:
<table>
<tbody data-bind="template: { name: 'rowTmpl', foreach: runners }">
</tbody>
</table>
<script id="rowTmpl" type="text/html">
<tr data-bind="template: { name: 'colTmpl', foreach: radios }" >
<td data-bind="text: name"></td>
<td data-bind="text: club"></td>
</tr>
</script>
<script id="colTmpl" type="text/html">
<td>aa</td>
</script>
#section Scripts{
<script src="/Scripts/knockout-1.3.0beta.js" type="text/javascript"></script>
<script type="text/javascript">
var vm = {
id: 1,
name: 'H21',
radios: ['2km', '4km', 'mål'],
runners: ko.observableArray([
{ name: 'Mikael Eliasson', club: 'Göteborg-Majorna OK', radios: ko.observableArray([{}, {}, {}]) },
{ name: 'Ola Martner', club: 'Göteborg-Majorna OK', radios: ko.observableArray([{}, {}, {}]) }
])
};
ko.applyBindings(vm);
</script>
}
My problem is that the tds inside colTmpl is not databoud, it's empty and placed after the third column with the text 'aa'. See this fiddle.
If you are using 1.3 beta (your fiddle is referencing the latest build), then you can do this:
<table>
<tbody data-bind="foreach: runners">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: club"></td>
<!-- ko foreach: radios-->
<td>aa</td>
<!-- /ko -->
</tr>
</tbody>
</table>
Sample here: http://jsfiddle.net/rniemeyer/bd7DT/
If you need to do this prior to 1.3 with jQuery templates, then you would want to pass the first item in your array into the template via templateOptions and do an {{if}} to check if you are on the first radio and render the two cells. Another option in jQuery templates is to use {{each}} around your dynamic cells rather than the foreach option of the template binding on the parent. You would lose some efficiency, if your columns are frequently changing dynamically. I can provide a sample for these two options, if necessary.
It is because of the fact that the content of <tr data-bind="template: { name: 'colTmpl', foreach: radios }" > is getting replaced by the template you specify.
If you instead do:
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: club"></td>
<td data-bind="template: { name: 'colTmpl', foreach: radios }" ></td>
</tr>
</script>
<script id="colTmpl" type="text/html">
<span> . aa . </span>
</script>
It will render.

Categories

Resources