Knockout Table : Highlight a Table Row - javascript

I have an Example Fiddle here. In this Table I wish to achieve Highlighting a Particular Row selected. If unselected Row should not be highlighted.
One of many sample I found Fiddle but I am unable to incorporate them inside my Example Fiddle Above.
Below is the HTML Code which shows basic Table.
<table id="devtable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr data-bind=" click: $parent.select ">
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Status"></td>
</tr>
</tbody>
ID :
Name :
Status :
Here is the knockout function to do manipulations
<Script>
var rowModel = function (id, name, status) {
this.ID = ko.observable(id);
this.Name = ko.observable(name);
this.Status = ko.observable(status);
};
var myData = [{
id: "001",
name: "Jhon",
status: "Single"
}, {
id: "002",
name: "Mike",
status: "Married"
}, {
id: "003",
name: "Marrie",
status: "Complicated"
}];
function MyVM(data) {
var self = this;
self.items = ko.observableArray(data.map(function (i) {
return new rowModel(i.id, i.name, i.status);
}));
self.select = function(item) {
self.selected(item);
self.enableEdit(true);
};
self.flashCss = ko.computed(function () {
//just an example
return 'flash';
});
self.selected = ko.observable(self.items()[0]);
self.enableEdit = ko.observable(false);
self.changeTableData = function() {
// How do I change the Data here and it should also reflect on the Page.
// If I do binding depending on condition it gives me error
if(true){
var myData = [{
id: "001",
name: "Jhon",
status: "Single"
}, {
id: "002",
name: "Mike",
status: "Married"
}, {
id: "003",
name: "Marrie",
status: "Complicated"
}];
}
else{
myData = [{
id: "111",
name: "ABC",
status: "Single"
}, {
id: "222",
name: "XYZ",
status: "Married"
}, {
id: "3333",
name: "PQR",
status: "Complicated"
}];
}
}
}
ko.applyBindings(new MyVM(myData));
</script>
CSS code below
.flash { background-color: yellow; }

You can use the css binding to add the .flash class based on the currently selected value:
<tr data-bind="click: $parent.select,
css: { flash: $parent.selected() === $data }">
...
</tr>
If you don't like this logic being defined in the view, you can pass a reference to the selected observable and create a computed property inside your RowModel:
var RowModel = function( /* ... */ selectedRow) {
// ...
this.isSelected = ko.pureComputed(function() {
return selectedRow() === this;
}, this);
}
Here's the quick fix in your fiddle:
http://jsfiddle.net/wa78zoe4/
P.S. if you want toggle-behavior, update select to:
self.select = function(item) {
if (item === self.selected()) {
self.selected(null);
self.enableEdit(false);
} else {
self.selected(item);
self.enableEdit(true);
}
};

Related

splice is creating NULL entry while removing the entry from an array

In my Angular5 application when I tried to remove the entries from the peoples array which is contained in selectedPersonArray using splice keyword is occasionally creating null entry in the peoples array. The code I have done looks like this:
import { Component } from '#angular/core';
import { DragulaService } from 'ng2-dragula/ng2-dragula';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedPersonArray = [];
peoples = [
{
id: 7,
firstName: 'Sobin 7',
lastName: 'Thomas 7'
}
];
people = [
{
id: 1,
firstName: 'First Name 1',
lastName: 'Last Name 1'
},
{
id: 2,
firstName: 'First Name 2',
lastName: 'Last Name 2'
},
{
id: 3,
firstName: 'First Name 3',
lastName: 'Last Name 3'
},
{
id: 4,
firstName: 'First Name 4',
lastName: 'Last Name 4'
}
];
toggleItemInArr(arr, item) {
const index = arr.indexOf(item);
index === - 1 ? arr.push(item) : arr.splice(index, 1);
}
addThisPersonToArray(person: any, event) {
if (!event.ctrlKey) {
this.selectedPersonArray = [];
}
this.toggleItemInArr(this.selectedPersonArray, person);
}
isPersonSelected(person: any) {
return (this.selectedPersonArray.indexOf(person) !== -1);
}
constructor(private dragula: DragulaService) {
dragula.setOptions('second-bag', {
copy: function (el, source) {
return source.id === 'source';
},
removeOnSpill: true,
copySortSource: false,
accepts: function(el, target, source, sibling) {
return target.id !== 'source';
}
});
}
ngOnInit() {
this.dragula
.out
.subscribe(value => {
for(let select of this.selectedPersonArray){
let i= 0;
for (let entry of this.peoples) {
if(entry.id == select.id){
let index = this.people.indexOf(select.id);
if (this.peoples.length >0){
this.peoples.splice(i, 1);
}
}
i++;
}
}
console.log("on after loop "+JSON.stringify( this.peoples));
this.selectedPersonArray.length = 0;
});
}
}
app.component.html
<table border=1 bgcolor="yellow">
<tbody id ='source' [dragula]='"second-bag"' [dragulaModel]="people">
<tr *ngFor="let person of people" >
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
<table border=2>
<tbody id ='dest' [dragula]='"second-bag"' [dragulaModel]="peoples">
<tr *ngFor="let person of peoples" (click)="addThisPersonToArray(person, $event)" [class.active]="isPersonSelected(person)">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
Actually what I want was is to delete multiple items selected using control key from 'dest' container of ng2-dragular second-bag.And it is working but it is creating null entries also
Can you try this?
this.peoples
.filter(people => !this.selectedPersonArray
.find(selectdPeople => people.id === selectdPeople.id)
);
I like the answer using filter and find. Here's another alternative using a loop.
I worked on a jsfiddle with what I suspect you were trying to do. Is this this is similar to what you intended?
I updated the search to work backwards so that the splice wouldn't alter the parts of the array that had not been searched through yet.
The jsfiddle can be found here: https://jsfiddle.net/vboughner/wfeunv2j/
this.selectedPersonArray = [
{
"id": "hello1",
"name": "something1"
},
];
this.peoples = [
{
"id": "hello1",
"name": "something1"
},
{
"id": "hello2",
"name": "something2"
},
{
"id": "hello3",
"name": "something3"
},
];
console.log(this.selectedPersonArray);
console.log(this.peoples);
for (let select of this.selectedPersonArray) {
for (let i = this.peoples.length - 1; i >= 0; i--) {
if (select.id == this.peoples[i].id) {
this.peoples.splice(i, 1);
}
}
}
console.log("on after loop " + JSON.stringify( this.peoples));
this.selectedPersonArray.length = 0;
The output looks like this:
on after loop [{"id":"hello2","name":"something2"},{"id":"hello3","name":"something3"}]

How to count the number of rows containing a certain value?

I'm using AngularJS and I have a table that I populate using ng-repeat. Check this short example:
http://jsfiddle.net/sso3ktz4/
How do I check how many rows I have with a certain value? For example, in the fiddle above, how do I check how many rows I have with the word "second"? It should return "3".
AngularJS answers are preferred, although I also have JQuery available.
Thanks!
updated controller code is below, where $scope.findRowCount is required function
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
$scope.findRowCount=function(value){
var count=0;
angular.forEach($scope.items, function(item, i){
if(item.name==value){
count=count+1;
}
angular.forEach(item.examples, function(exp, j){
if(exp.name==value){
count=count+1;
}
})
});
console.log("count"+count);
return count;
}
var result=$scope.findRowCount("second");
console.log(result);
}
http://jsfiddle.net/p3g9vyud/
Try this way
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
//Get sum based on the label
$scope.getTotalByLabel = function(keyword)
{
$scope.totalSecond = 0;
angular.forEach($scope.items, function(value, key) {
if(value.name == keyword)
{
$scope.totalSecond += 1;
}
angular.forEach(value.examples, function(val, k) {
if(val.name == keyword)
{
$scope.totalSecond += 1;
}
});
});
return $scope.totalSecond;
}
}
th,
td {
padding: 7px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<table border="1">
<tbody ng:repeat="i in items">
<tr>
<td>{{i.name}}</td>
<td>{{$index}}</td>
</tr>
<tr ng:repeat="e in i.examples">
<td>{{e.name}}</td>
<td>{{$index}}</td>
</tr>
</tbody>
</table>
<b>Total of second</b>: {{getTotalByLabel('second')}}
</div>
</div>

Knockout group list into smaller lists with objects

I have daily data for multiple employees and depending on the start time and end time that could mean a lot of data.
So with the mapping plugin i mapped them into one big list, but i will need them grouped by employee into smaller lists so i can make a tables per employee (like smaller view models) that has filtering and sorting for that subset of data.
Here is a basic example i created with static data.
$(function () {
var data = {
Employees: [{
Id: 1,
Name: "Employee1",
Day: new Date(),
Price: 12.54
}, {
Id: 2,
Name: "Employee2",
Day: new Date(),
Price: 112.54
}, {
Id: 1,
Name: "Employee1",
Day: new Date(),
Price: 12.54
}, {
Id: 3,
Name: "Employee3",
Day: new Date(),
Price: 12.54
}]
};
// simulate the model to json conversion. from now on i work with the json
var jsonModel = JSON.stringify(data);
function employeeModel(data) {
var employeeMapping = {
'copy': ["Id", "Name", "Day", "Price"]
};
ko.mapping.fromJS(data, employeeMapping, this);
}
function employeeViewModel(data) {
var self = this;
var employeesMapping = {
'Employees': {
create: function (options) {
return new employeeModel(options.data);
}
}
};
ko.mapping.fromJSON(data, employeesMapping, self);
}
var productsModel = new employeeViewModel(jsonModel);
ko.applyBindings(productsModel);
});
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
tr:nth-child(even) {
background-color: white;
}
tr:nth-child(odd) {
background-color: #C1C0C0;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<table>
<tbody data-bind="foreach: Employees">
<tr>
<td><span data-bind="text:Id"></span>
</td>
<td><span data-bind="text:Name"></span>
</td>
<td><span data-bind="text:Day"></span>
</td>
<td><span data-bind="text:Price"></span>
</td>
</tr>
</tbody>
</table>
One possibility would be to use a computed value to group your data.
self.EmployeeGroups = ko.pureComputed(function () {
var employees = self.Employees(),
index = {},
group = [];
ko.utils.arrayForEach(employees, function(empl) {
var id = ko.unwrap(empl.Id);
if ( !index.hasOwnProperty(id) ) {
index[id] = {
grouping: {
Id: empl.Id,
Name: empl.Name
},
items: []
};
group.push(index[id]);
}
index[id].items.push(empl);
});
return group;
});
would turn your data from a flat array to this:
[{
grouping: {
Id: /* ... */,
Name: /* ... */
}
items: [/* references to all employee objects in this group */]
}, {
/* same */
}]
Expand the code snippet below to see it at work.
$(function () {
var data = {
Employees: [{
Id: 1,
Name: "Employee1",
Day: new Date(),
Price: 12.54
}, {
Id: 2,
Name: "Employee2",
Day: new Date(),
Price: 112.54
}, {
Id: 1,
Name: "Employee1",
Day: new Date(),
Price: 12.54
}, {
Id: 3,
Name: "Employee3",
Day: new Date(),
Price: 12.54
}]
};
var jsonModel = JSON.stringify(data);
function employeeModel(data) {
var employeeMapping = {
'copy': ["Id", "Name", "Day", "Price"]
};
ko.mapping.fromJS(data, employeeMapping, this);
}
function employeeViewModel(data) {
var self = this;
self.Employees = ko.observableArray();
self.EmployeeGroups = ko.pureComputed(function () {
var employees = self.Employees(),
index = {},
group = [];
ko.utils.arrayForEach(employees, function(empl) {
var id = ko.unwrap(empl.Id);
if ( !index.hasOwnProperty(id) ) {
index[id] = {
grouping: {
Id: empl.Id,
Name: empl.Name
},
items: []
};
group.push(index[id]);
}
index[id].items.push(empl);
});
return group;
});
// init
var employeesMapping = {
'Employees': {
create: function (options) {
return new employeeModel(options.data);
}
}
};
ko.mapping.fromJSON(data, employeesMapping, self);
}
var productsModel = new employeeViewModel(jsonModel);
ko.applyBindings(productsModel);
});
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
tr:nth-child(even) {
background-color: #efefef;
}
tr:nth-child(odd) {
background-color: #CCCCCC;
}
tr.subhead {
background-color: #D6E3FF;
font-weight: bold;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<table>
<!-- ko foreach: EmployeeGroups -->
<tbody>
<!-- ko with: grouping -->
<tr class="subhead">
<td colspan="2">
<span data-bind="text: Id"></span>
<span data-bind="text: Name"></span>
</td>
</tr>
<!-- /ko -->
<!-- ko foreach: items -->
<tr>
<td><span data-bind="text: Day"></span></td>
<td><span data-bind="text: Price"></span></td>
</tr>
<!-- /ko -->
</tbody>
<!-- /ko -->
</table>
<pre data-bind="text: ko.toJSON($root, null, 2)" style="font-size: smallest;"></pre>

KnockoutJS Paged Grid example with a pageSize drop-down

Working from the KO example found here: http://knockoutjs.com/examples/grid.html,
I want to add a drop-down to select different page sizes (e.g. 4, 8, 12 items per page) and update the page grid upon changing the drop-down.
tried a bunch of things and I know I am missing something to get this to work. Thanks in advance for any help or a link to an existing solution.
What I sort of have now:
=== View ===
<div data-bind='simpleGrid: gridViewModel'> </div>
<select class="form-control" name="displayCount" id="displayCount" data-bind="value: valueDisplayCount;">
<option value="4">4</option><option value="8">8</option><option value="16">16</option>
</select>
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
==== View Model =====
$( document ).ready(function(){
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Furious Lizard", sales: 152, price: 25.00 },
{ name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ name: "Brooding Dragon", sales: 0, price: 6350 },
{ name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var PagedGridModel = function(items) {
this.items = ko.observableArray(items);
this.valueDisplayCount = ko.observable(4);
this.sortByName = function() {
this.items.sort(function(a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function() {
this.gridViewModel.currentPageIndex(0);
};
this.valUpdDisplayCount= function(){
alert($('#displayCount').val());
this.gridViewModel.pageSize(6);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: this.valueDisplayCount
});
};
ko.applyBindings(new PagedGridModel(initialData));
});
JSFiddle:
http://jsfiddle.net/RNunc/1/
You would need to tweak the simplegrid code to look for an observable for pageSize. The updates could look like:
ko.simpleGrid = {
// Defines a view model class you can use to populate a grid
viewModel: function (configuration) {
this.data = configuration.data;
this.currentPageIndex = ko.observable(0);
this.pageSize = configuration.pageSize || ko.observable(5);
// If you don't specify columns configuration, we'll use scaffolding
this.columns = configuration.columns || getColumnsForScaffolding(ko.unwrap(this.data));
this.itemsOnCurrentPage = ko.computed(function () {
var size = ko.unwrap(this.pageSize);
var startIndex = size * this.currentPageIndex();
return ko.unwrap(this.data).slice(startIndex, startIndex + size);
}, this);
this.maxPageIndex = ko.computed(function () {
return Math.ceil(ko.unwrap(this.data).length / ko.unwrap(this.pageSize)) - 1;
}, this);
}
};
The simplegrid code is here: http://knockoutjs.com/examples/resources/knockout.simpleGrid.3.0.js
http://jsfiddle.net/rniemeyer/82MAR/

Nested menu using parent id in knockoutJs

I am try to create nested menu using given json data by the client.
Data :
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuDocuments",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
I am trying like this :
var Menu = function(dept, all) {
var self = this;
this.id = dept.Id;
this.name = ko.observable(dept.Text);
this.parentId = dept.ParentId;
this.children = ko.observableArray();
ko.utils.arrayForEach(all || [], function(menu) {
if(menu.ParentId){
if (menu.ParentId === self.id) {
self.children.push(new Menu(menu, all));
}
}else{
new Menu(menu, all)
}
});
};
var ViewModel = function(data) {
this.root = new Menu(data[0], data);
};
$(function() {
ko.applyBindings(new ViewModel(serverData));
});
Templates :
<div data-bind="with: root">
<ul data-bind="template: 'deptTmpl'">
</ul>
</div>
<script id="deptTmpl" type="text/html">
<li>
<a data-bind="text: name"></a>
<ul data-bind="template: { name: 'deptTmpl', foreach: children }">
</ul>
</li>
</script>
problem is that its only work when 2nd and 3rd object has parent ID. i am trying something like it should make nested menu according to given json data. so id there is no parent id on object it should add on root. and if object has parent id it should add according to parent id.
Please help me to correct my code or guide me if these is another way to do this in KnockoutJS.
Thanks
This should help you http://jsfiddle.net/MCNK8/3/, the main idea is to rebuild main data array, by placing child inside parent
HTML
<script id="nodeTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
</li>
</script>
<script id="nodeLeafTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
</li>
</script>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
Javascript (#see fiddle)
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
ParentId: 'menuColorSearch',
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuReports",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
ParentId: 'menuReports',
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
function getNestedMenu(index, all) {
var root = all[index];
if(!root){
return all;
}
if(!all[index].children){
all[index].children = [];
}
for(var i = 0; i < all.length; i++){
//<infinity nesting?>
//put children inside it's parent
if(all[index].Id == all[i].ParentId){
all[index].children.push(all[i]);
all[i].used = true;
}
//this is needed for each item, to determine which template to use
all[index].nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</infinity nesting?>
}
return getNestedMenu(++index, all);
};
function getModel(data) {
var items = getNestedMenu(0, data);
//<remove duplicates, for infinity nesting only>
for(var i = 0; i < items.length; i++){
if(items[i].used){
items.splice(i, 1);
i--;
}
}
//</remove duplicates, for infinity nesting only>
//<build root item>
var model = {};
model.children = ko.observableArray(items);
model.nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</build root item>
console.log(items);
return model;
};
(function() {
//new ViewModel(serverData);
ko.applyBindings(getModel(serverData));
})();

Categories