Kendo Grid Change Sequence of fields - javascript

I want to shuffle the fields in popup when ever i add or edit the record
In this below fiddle example Grid view Columns are in sequence like First Name,LastName,Cities But when ever i do add or Edit in popup first i want sequence of fields to be like Cities, LastName, FistName.
Jsfiddle Link
<div id="grid"></div>
var firstNames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Nige"];
var lastNames = ["Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "King", "Callahan", "Dodsworth",
"White"];
var cities = ["Seattle", "Tacoma", "Kirkland", "Redmond", "London", "Philadelphia", "New York",
"Seattle", "London", "Boston"];
function createRandomData(count) {
var data = [],
now = new Date();
for (var i = 0; i < count; i++) {
var firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
var lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
var city = [];
for (var j = 0; j < Math.floor(Math.random() * 3 + 1); j++) {
city.push(cities[Math.floor(Math.random() * cities.length)]);
}
data.push({
Id: i + 1,
FirstName: firstName,
LastName: lastName,
Cities: city
});
}
return data;
}
function citiesEditor(container, options) {
$("<select multiple='multiple' " +
"data-bind='value : Cities'/>").appendTo(container).kendoMultiSelect({
dataSource: cities
});
}
var ds = new kendo.data.DataSource({
transport: {
read: function (op) {
op.success(createRandomData(300));
},
update: function (op) {
alert("update: " + JSON.stringify(op, null, 2));
op.success(op.data);
}
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: {
type: 'number'
},
FirstName: {
type: 'string'
},
LastName: {
type: 'string'
}
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: ds,
editable: "popup",
pageable: {
refresh: true,
pageSizes: true
},
columns: [{
command: "edit",
width: 100
}, {
field: "FirstName",
width: 100,
title: "First Name"
}, {
field: "LastName",
width: 100,
title: "Last Name"
}, {
field: "Cities",
width: 300,
editor: citiesEditor,
template: "#= Cities.join(', ') #"
}]
}).data("kendoGrid");
How to shuffle fields on Add and Edit Popup.

Related

how to filter Drop down in javascript

I am having
const Fruits = [
{ name: "Apple", code: "1" },
{ name: "Orange", code: "2" },
{ name: "Mango", code: "3" },
{ name: "Derry", code: "4" }
];
const SelectedFruits=[]
if user selects Apple from drop down i need to remove it from Fruits and add it to SelectedFruits like priority wise he can change them please help me and again if user can change the priority.
Hope this is what you are looking for !!
const Fruits = [
{ name: "Apple", code: "1" },
{ name: "Orange", code: "2" },
{ name: "Mango", code: "3" },
{ name: "Derry", code: "4" }
];
const fruitsSel = document.querySelector('#fruits');
Fruits.forEach(function(item, index, array) {
var opt = document.createElement("option");
opt.text = item.name;
opt.value = item.code;
fruitsSel.add(opt);
});
const SelectedFruits=[];
const remainingFruits = [];
fruitsSel.addEventListener('change',(e)=>{
const val = e.target.value;
const selectedFruit = Fruits.filter(fruit=>fruit.code===val);
SelectedFruits.push(...selectedFruit);
const remFruits = Fruits.filter(fruit=>fruit.code!==val);
remainingFruits.push(...remFruits);
console.log({'selected fruit' : selectedFruit})
console.log({'remaining fruits' : remFruits})
})
<select id='fruits'>
</select>
let searchData: { [key: string]: Object; }[] = [
{ Index: "s1", Country: "Alaska" }, { Index: "s2", Country: "California" },
{ Index: "s3", Country: "Florida" }, { Index: "s4", Country: "Georgia" }
];
let filter: DropDownList = new DropDownList({
dataSource: searchData,
// map the appropriate column
fields: { text: "Country", value: "Index" },
// set placeholder to DropDownList input element
placeholder:"Select a country",
// set true to allowFiltering for enable filtering supports
allowFiltering: true,
//Bind the filter event
filtering: function (e: FilteringEventArgs) {
let query = new Query();
//frame the query based on search string with filter type.
query = (e.text != "") ? query.where("Country", "startswith", e.text, true) : query;
//pass the filter data source, filter query to updateData method.
e.updateData(searchData, query);
}
});
filter.appendTo('#ddlelement');
you can do like this.

Populating slickgrid(JS) with PHP array

I have this huge slickgrid that users can fill with data. once filled in the data is sent to the server-side with AJAX and then to the database with PHP. then I get the data out of the database and put it inside a PHP array. Now how do I populate the slickgrid with that array data. I cant seem to find the solution to this. because How to I get that php array inside the javascript slickgrid file.
javascript slickgrid for information:
<script type ='text/javascript'>
var gridArray;
var editedRows = []
function CreateColumns() {
var columns = [
{id: "hours", name: "uren", field: "hours"},
{id: "Total_inspection", name: "totaal inspectie", field: "Total_inspection", editor: Slick.Editors.Integer},
{id: "Per_hour_inspection", name: "Per uur", field: "Per_hour_inspection"},
{id: "Total_losses", name: "Totaal uitstoot", field: "Total_losses",editor: Slick.Editors.Integer},
{id: "Per_hour_losses", name: "Per uur", field: "Per_hour_losses"},
{id: "%_spil", name: "% Spil", field: "%_spil"},
{id: "%_cumul", name: "% Cumul", field: "%_cumul"},
{id: "Operator", name: "Operator", field: "Operator",editor: Slick.Editors.Text},
{id: "SKU", name: "SKU", field: "SKU",editor: Slick.Editors.Text},
{id: "End_SKU", name: "Tellerstand einde SKU", field: "End_SKU"},
{id: "Batch", name: "Batch", field: "Batch"}
];
return columns;
}
function CreateOptions() {
var options = {
editable: true,
enableCellNavigation: true,
enableColumnReorder: false,
autoEdit :false
};
return options;
}
var data = [];
function CreateData() {
for (var i = 0; i < 8; i++) {
data[i] = {
hours: 6+i+"U",
};
}
return data;
}
console.log(data)
function CreateGrid(elementId) {
if (!gridArray) { gridArray = []; }
var data = CreateData();
//editedRows.push(data)
var grid = new Slick.Grid("#" + elementId,data, CreateColumns(), CreateOptions());
gridArray[length] = grid;
//todo tets localstorage
var columnidx = data[0].Total_inspection
var columnidx2 = data[0].Total_losses
var calculation = columnidx2/columnidx
var columnidx3 = data[0].Per_hour_inspection
//push(calculation)
var columnid = data[columnidx]
//console.log(calculation,columnidx3)
grid.onCellChange.subscribe(function (e,args) {
//console.log('arguments',args.item);
editedRows.push(args.item)
console.log('arrayrows',editedRows)
});
}
console.log(editedRows)
$('#Savebtn').click(function () {
console.log(editedRows);
//var UpdatedRows = JSON.stringify(editedRows);
//console.log(UpdatedRows);
$.ajax({
type: "POST",
url: "request.php",// changed
data: {arrayOfValues: editedRows},
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
alert(data)
console.log(data)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
PHP looks like this :
$stmt = $mysqli->prepare("SELECT * FROM kicdata");
//$stmt->bind_param('i',$id);
$stmt->execute();
$result = $stmt->get_result();
$return_data = [];
while($row = $result->fetch_assoc()){
$return_data[]= $row;
}
var_dump($return_data);
UPDATE: the use of ajax solved the part to send the server-side array to the client-side.

create pagination for search filter along with sorting table using knockout js

I am creating table with pagination and search filter. We bind table data with search filter, Is the possible to crate search filter in table with pagination. How to create pagination in table, and also perform search filter, along with sorting also.
function PlayersViewModel() {
var self = this,x, i, suits;
/* text field should be empty */
self.filterText = ko.observable(""); // Text from search field
//#region Constant Properties
self.descending = "fa fa-arrow-down";
self.ascending = "fa fa-arrow-up";
//#endregion
self.CurrentPage = ko.observable(1); // Store the current page of the user
self.DataPerPage = ko.observable(5); // To identify how many data we want to see per page
//#region Knockout Observables
// Observable array that represents each column in the table
self.columns = ko.observableArray([
{ property: "id", header: "ID", type: "number", state: ko.observable("") },
{ property: "name", header: "Name", type: "string", state: ko.observable("") },
{ property: "time", header: "Time", type: "date", state: ko.observable("") },
{ property: "dob", header: "Date of Birth", type: "date", state: ko.observable("") },
{ property: "address", header: "Address", type: "string", state: ko.observable("") },
{ property: "msg", header: "Body", type: "string", state: ko.observable("") }
]);
// Observable array that will be our data
self.players = ko.observableArray([
{ id: "01", name: "Micky", time: "2015-02-09 4:46:56.678", dob: "10/20/1974", address: "London", msg: "Received Message" },
{ id: "02", name: "Griffey", time: "2015-03-09 4:46:54.678", dob: "11/21/1969", address: "Russia", msg: "Received Message" },
{ id: "03", name: "Derek", time: "2015-01-07 4:46:55.678", dob: "6/26/1931", address: "London", msg: "Send Message" },
{ id: "04", name: "Steven", time: "2015-03-09 4:46:56.678", dob: "2/10/1963", address: "Russia", msg: "Send Message" },
{ id: "05", name: "Jafer", time: "2015-02-09 5:46:56.540", dob: "12/18/1886", address: "London", msg: "Received Message" },
{ id: "06", name: "Jenifer", time: "2015-01-14 4:52:16.379", dob: "11/29/1970", address: "China", msg: "Send Message" },
{ id: "07", name: "Jones", time: "2015-03-08 5:26:33.600", dob: "8/24/1895", address: "London", msg: "Received Message" },
{ id: "08", name: "Micky", time: "2015-02-09 4:46:56.678", dob: "10/20/1974", address: "London", msg: "Received Message" },
{ id: "09", name: "Bruce", time: "2015-03-09 4:46:54.678", dob: "11/21/1969", address: "Russia", msg: "Received Message" },
{ id: "10", name: "Peter", time: "2015-01-07 4:46:55.678", dob: "6/26/1931", address: "London", msg: "Send Message" },
{ id: "11", name: "Wayne", time: "2015-03-09 4:46:56.678", dob: "2/10/1963", address: "Russia", msg: "Send Message" },
{ id: "12", name: "Sam", time: "2015-02-09 5:46:56.540", dob: "12/18/1886", address: "London", msg: "Received Message" },
{ id: "13", name: "Jenifer", time: "2015-01-14 4:52:16.379", dob: "11/29/1970", address: "China", msg: "Send Message" },
{ id: "14", name: "Smith", time: "2015-03-08 5:26:33.600", dob: "8/24/1895", address: "London", msg: "Received Message" }
]);
//#endregion
/* script for search filter */
suits = self.players();
for ( i = 0; i < suits.length; i++) {
suits[i]["search_content"] = ">";
for ( x in suits[i] ) {
if ( !suits[i].hasOwnProperty(x) || x == "search_content" || typeof suits[i][x] !== "string") {continue;}
suits[i]["search_content"] += suits[i][x].toUpperCase();
}
}
// Collection of players after going through search filter
self.filteredTestsuites = ko.computed(function () {
var reg;
// If many white spaces in a row, replace with only one white space
fText = self.filterText().replace(/\s+/gi, '|');
fText = fText.replace(/\|\s*$/gi, '');
console.log("regex:", fText);
reg = new RegExp(fText, "gi");
// If there is anything in the search box, filter for this
// As of now this does not divide the filterText and only searches the Name field
var filteredCollection = ko.utils.arrayFilter(self.players(), function(test) {
if(fText.length)
return test.search_content.match(reg);
else
return 1;
});
return filteredCollection;
}, self);
/* script Ends with text search */
/* script for sorting */
//#region Sorting methods
self.sortClick = function (column) {
try {
// Call this method to clear the state of any columns OTHER than the target
// so we can keep track of the ascending/descending
self.clearColumnStates(column);
// Get the state of the sort type
if (column.state() === "" || column.state() === self.descending) {
column.state(self.ascending);
}
else {
column.state(self.descending);
}
console.log(column.state());
console.log(column.type);
switch (column.type) {
case "number":
self.numberSort(column);
break;
case "date":
self.dateSort(column);
break;
case "string":
default:
self.stringSort(column);
break;
}
}
catch (err) {
// Always remember to handle those errors that could occur during a user interaction
alert(err);
}
};
// Generic sort method for numbers and strings
self.stringSort = function (column) { // Pass in the column object
self.players(self.players().sort(function (a, b) {
// Set strings to lowercase to sort properly
var playerA = a[column.property].toLowerCase(), playerB = b[column.property].toLowerCase();
if (playerA < playerB) {
return (column.state() === self.ascending) ? -1 : 1;
}
else if (playerA > playerB) {
return (column.state() === self.ascending) ? 1 : -1;
}
else {
return 0
}
}));
};
self.numberSort = function (column) {
self.players(self.players().sort(function (a, b) {
var playerA = a[column.property], playerB = b[column.property];
if (column.state() === self.ascending) {
return playerA - playerB;
}
else {
return playerB - playerA;
}
}));
};
// Sort by date
self.dateSort = function (column) {
self.players(self.players().sort(function (a, b) {
if (column.state() === self.ascending) {
return new Date(a[column.property]) - new Date(b[column.property]);
}
else {
return new Date(b[column.property]) - new Date(a[column.property]);
}
}));
};
//#region Utility Methods
self.clearColumnStates = function (selectedColumn) {
var otherColumns = self.columns().filter(function (col) {
return col != selectedColumn;
});
for (var i = 0; i < otherColumns.length; i++) {
otherColumns[i].state("");
}
};
/* script Ends for sorting */
};
ko.applyBindings(new PlayersViewModel());
They should perform search filter and sorting in the table correctly, how to create pagination for the sample, they do not affect the search filter and sorting in the table.
The basics of pagination using a ko.pureComputed:
const paginatedData = ko.pureComputed(
() => dataSource().slice(
currentPage() * pageSize(),
currentPage() * pageSize() + pageSize()
)
);
In your specific case, dataSource is filteredTestsuites, currentPage is CurrentPage and pageSize is DataPerPage.
Things to keep in mind:
- Fix the lower limit of currentPage to 0
- Fix the upper limit of currentPage to Math.floor(dataSource().length)
- Make sure that when the dataSource changes in length (i.e. when filtering), the currentPage is updated to match the new restrictions
- Make sure that when pageSize is made larger, the currentPage is updated to match the new restrictions.
const currentPage = ko.observable(0);
const pageSize = ko.observable(5);
const dataSource = ko.observableArray(
Array.from({ length: 100 }, (_, i) => i)
);
const paginatedData = ko.pureComputed(
() => dataSource().slice(
currentPage() * pageSize(),
currentPage() * pageSize() + pageSize()
)
);
ko.applyBindings({
next: () => currentPage(currentPage() + 1),
prev: () => currentPage(currentPage() - 1),
currentPage,
paginatedData
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: paginatedData">
<li data-bind="text: $data"></li>
</ul>
<button data-bind="click: prev"><</button>
<span data-bind="text: currentPage"></span>
<button data-bind="click: next">></button>

ASP MVC Net using Check list kendo Grid

How to get data from kendogrid2 and set it to kendogrid1?
I have the 2 kendogrid using checklist grid.
This is the jquery code:
$("#btnAddPortfolio").click(function () {
var grid2 = $("#portfolioGrid2").data("kendoGrid");
var dt = grid2.dataItem
var ds = new kendo.data.DataSource({
data: [{ "Portfolio": "Data of checklist selected item"}]
});
$("#portfolioGrid1").data("kendoGrid").setDataSource(ds);
$('#grid2_modal').modal('toggle');
});
How to get the value of selected item on #portofolioGrid2?
A simple way to achieve it:
$("#grid1").kendoGrid({
dataSource: {
data: [{ Name: "John Doe" }, { Name: "Jane Doe" },
{ Name: "Doe John" }, { Name: "Doe Jane" }]
},
columns: [{
template: '<input type="checkbox" />',
width: 40
}, {
field: "Name"
}]
});
$("#grid2").kendoGrid({
columns: [{
field: "Name"
}]
});
$("#transfer-items").on("click", function() {
let grid1 = $("#grid1").data("kendoGrid"),
grid2 = $("#grid2").data("kendoGrid"),
$checkboxes = grid1.tbody.find('input:checked').toArray();
if ($checkboxes.length) {
$checkboxes.forEach($chk => {
let item = grid1.dataItem($chk.closest("tr"));
grid2.dataSource.add(item);
});
}
else {
window.alert("No item has been selected.");
}
});
Demo

How do i correctly put a $scope.$watch on a two dimensional array?

Putting an Angular watch on a multidimensional array is proving problematic
I have a screen where the user will see two teams (outer array) with a teamsheet(inner array) for each team. He is able to drag and drop the players to change the batting order.
The battingOrder is updated according to the player's spot in the array.
The following solution is a bit of a cop out/short term, but it does solve my immediate stumbling block.
A more preferable solution would be appreciated though.
The following code is in my controller.
$scope.$watch(
"Teams[0].TeamSheet",
function (newValue, oldValue) {
for (var i = 0; i < newValue.length; i++) {
newValue[i].battingOrder = i + 1;
}
},
true
);
$scope.$watch(
"Teams[1].TeamSheet",
function (newValue, oldValue) {
for (var i = 0; i < newValue.length; i++) {
newValue[i].battingOrder = i + 1;
}
},
true
);
$scope.Teams = [{
TeamName: "South-Africa",
TeamSheet: [
{
name: "A Peterson",
battingOrder: 1,
mode: "view"
},
{
name: "Riley Rossouw",
battingOrder: 2,
mode: "view"
},
{
name: "H Amla",
battingOrder: 3,
mode: "view"
},
{
name: "F Du Plessis",
battingOrder: 4,
mode: "view"
},
{
name: "AB De Villiers",
battingOrder: 5,
mode: "view"
}
]
},
{
TeamName: "Australia",
TeamSheet: [
{
name: "D Warner",
battingOrder: 1,
mode: "view"
},
{
name: "S Watson",
battingOrder: 2,
mode: "view"
},
{
name: "M Clarke",
battingOrder: 3,
mode: "view"
},
{
name: "C Rogers",
battingOrder: 4,
mode: "view"
},
{
name: "S Smith",
battingOrder: 5,
mode: "view"
}
]
}];
you can try to update batting order directly inside the view:
<div ng-repeat="member in team" ng-init="member.battingOrder = $index">
</div>
then you do not need to use $watch
EDIT
the previous solution will not work after you swap items in your array. Use the following code to overcome this problem:
<body ng-controller="MainCtrl">
<div ng-repeat="member in team">
{{setIndex(member,$index)}}
{{member.name}},{{member.index}}
</div>
<button ng-click="swap()">swap first with last</button>
</body>
controller:
app.controller('MainCtrl', function($scope) {
$scope.team = [ { index: 0, name : 'first' }, { index: 0, name : 'second' }, { index: 0, name : 'third' } ];
$scope.swap = function () {
var tmp = $scope.team[0];
$scope.team[0] = $scope.team[2];
$scope.team[2] = tmp;
}
$scope.setIndex = function (member, index)
{
member.index = index;
}
});
http://plnkr.co/edit/V3ixkww7dxcx8uZ7f0hj?p=preview

Categories

Resources