Dispaly JSON data in Kendo UI Grid - javascript

Hi I have Created a html, java script. I am able to bind the json data to kendo UI dropdown list and able to display that list on Html page . When is select any data in the list I am able to retrieve the selected value . Now I am trying to replace the drop down list with kendo ui grid and want to retrieve the selected row cells value . below is the code for kendo drop down list . Help would be highly appreciated.
HTML file
<table style="padding-top: 20px; padding-left: 10px; display: table;" id="selectAccountTable"> <tbody>
<tr>
<td>Existing Account Found</td>
</tr>
<tr>
<td>
<!--need to display kendo grid UI , kendo drop down is created at this input
<input id="accountSelect" style="width: 350px;">
</td>
</tr>
JavaScript code
function DisplayActiveAccounts(res)
{
var accounts = [];
var response = $.parseJSON(res);
for (var idx = 0; idx < response.length; idx++)
{
accounts.push({ 'name': response[idx].Name, 'id': response[idx].Id, 'code':
response[idx].Code,'city':response[idx].City,'state':response[idx].State,'ce':response[idx].CE});
}
$('#selectAccountTable').show();
selectAccountVisible = true;
//need to create kendo ui grid instead of kendo ui drop down list
$('#accountSelect').kendoDropDownList({
dataTextField: "name",
dataValueField: "accountid",
dataSource: accounts
});
}
function _okClick()
{
if (closeWindow) {
//If the account select table is visible pass back selected account code
//need to retrieve the selected row values in returnValues variable
if (selectAccountVisible) {
var dropDownSelect = $("#accountSelect").data ("kendoDropDownList");
var listData = dropDownSelect.dataSource;
//Get data from selecte value in drop down
var selectedData = listData._data.filter(function (account) { return account.id == dropDownSelect.value() });
var returnValues = { testID: selectedData[0].id, testCode: selectedData[0].code };
}
closeWindow();
}
}

Related

How do I add a blank row to table using FooTable v3

FooTable v2 allowed users to inject DOM elements - rows into a table - and sorting still kinda works. FooTable v3 is a complete re-write and the data in the table is completely managed by FooTable. The original DOM is restructured by FooTable.init. Adding to the DOM will mean FooTable sorting and filtering will be unaware of the added record. As far as I can tell, the proper way to add a new row to the FooTable v3 is to call the editing component's function 'addRow'.
The original author of FooTable has assumed many things - such as the developer will want to use a popup asking for values. In my case, when adding a row I do not want an editor window popping up asking for values. I merely want to add a blank row to the table programatically/dynamically without using any footable UI components.
How do I call this function? What is the proper syntax.
I init my table via ...
$(document).ready(function () {
$('.my-footable').footable({
"editing": {
"enabled":"true"
}
});
});
... and I have a click event on a button...
$(document).on("click", "#myButton", function (event) {
var editing = FooTable.get(".my-footable").use(FooTable.Editing);
});
... but I am stumped on how to invoke addRow - and what parameters I pass...
Any ideas?
$(document).ready(function() {
var columns_name = ['id', 'first name', 'last name', 'job title'],
columns = [],
rows = [{
'id': 1,
'first_name': 'Dennise',
'last_name': 'Fuhrman',
'job_title': 'High School History Teacher'
}];
/**
Creating a new object with the help of columns_name array with
having key title and name and then pushing it to the columns array. We'll
pass that array in the footable init object.
*/
for (var i = 0; i < columns_name.length; i++) {
var column = columns_name[i];
/**
In name key replacing spaces with underscore so that it will match with
the keys in row array of object
*/
columns.push({
title: column,
name: column.replace(/ /g, "_")
});
}
var ft_init_options = {
columns: columns,
rows: rows,
editing: {
enabled: true,
alwaysShow: true,
allowAdd: true,
allowEdit: false,
addRow: function() {
/**
Creating new row with empty columns having input field
*/
var values = {
'id': '<input type="text">',
'first_name': '<input type="text">',
'last_name': '<input type="text">',
'job_title': '<input type="text">'
}
ft.rows.add(values);
},
deleteRow: function(row) {
if (confirm('Are you sure you want to delete the row?')) {
row.delete();
}
}
}
};
var ft = FooTable.init('#editing-example', ft_init_options);
});
/**
Remove the following comments if you want to remove the border from the inputs
and want to display when they are in focus
*/
/**
textarea:focus, input:focus{
border-width: 2px;
border-style: inset;
border-color: initial;
border-image: initial;
}
textarea, input {
border : none;
}
**/
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://fooplugins.github.io/FooTable/compiled/footable.bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/3.1.6/footable.js"></script>
<div class="container-fluid">
<hr>
<h1 class="text-center"> FooTable Editing Example with inputs in row</h1>
<hr>
<table id="editing-example" class="table"></table>
</div>
If code snippet is not working then have a look on jsfiddle

dojo dstore insert row

Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.
// Clone a row
theTable = tmxdijit.registry.byId(tableName);
firstRow = theTable.collection.data[theTable.collection.data.length-1];
firstRowDom = theTable.row(firstRow.id);
var cloneRow = json.stringify(firstRow);
cloneRow = json.parse(cloneRow);
// Get the row I want to add before
var theSelected = Object.keys(theTable.selection)[0];
if(theSelected.length > 0) {
var theRowID = theSelected[0];
}
theTable.collection.add(cloneRow, {beforeId: theRowID});
theTable.renderArray([cloneRow]);
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.
For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:
var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
columns: { /* columns */ },
collection: store
});
By default dstore assumes the id property is "id", but you can specify something else:
var store = new StoreClass({ idProperty: "name", data: whatever });
If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):
grid.set('sort', 'name');
To add or remove data, use the store methods put and remove.
var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);
The grid will be notified of the store update and will insert or remove the rows.
The dgrid Using Grids and Stores tutorial has more information and examples.
Instead of this, why don't you add the data directly to the grid store? See if this helps
https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
Adding and Deleting data
If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
.
<div>
This example shows, how to add/remove rows
</div>
<table data-dojo-type="dojox.grid.DataGrid"
data-dojo-id="grid5"
data-dojo-props="store:store3,
query:{ name: '*' },
rowsPerPage:20,
clientSort:true,
rowSelector:'20px'
style="width: 400px; height: 200px;">
<thead>
<tr>
<th width="200px"
field="name">Country/Continent Name</th>
<th width="auto"
field="type"
cellType="dojox.grid.cells.Select"
options="country,city,continent"
editable="true">Type</th>
</tr>
</thead>
</table>
<div data-dojo-type="dijit.form.Button">
Add Row
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// set the properties for the new item:
var myNewItem = {type: "country", name: "Fill this country name"};
// Insert the new item into the store:
// (we use store3 from the example above in this example)
store3.newItem(myNewItem);
</script>
</div>
<div data-dojo-type="dijit.form.Button">
Remove Selected Rows
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// Get all selected items from the Grid:
var items = grid5.selection.getSelected();
if(items.length){
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
// Delete the item from the data store:
store3.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
</script>
</div>
.
#import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
#import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";

Display no results using Angular Kendo for kendo list view

I am using Angular Kendo and building one list.
<kendo-mobile-list-view id="myList" class="item-list" k-template="templates.myListTemp" k-data-source="myService.myDataSource">
</kendo-mobile-list-view>
I am using Kendo DataSource and ObservableArray for generating data for my list in my service.
this.myDataSource = new kendo.data.DataSource({ data:this.myObservableArray });
this.myObservableArray.push({ key: "test", id:"test" });
Every is working as expected.
Now I want to display a message when their are no records to display, in the place I am displaying the list, like "NO RECORDS TO DISPLAY, Please Refresh".
How can I achieve this using angular Kendo.
I saw few posts for Kendo JQuery but no solution for Angular Kendo.
Define the grid
$('#grid').kendoGrid({
dataSource: employeeDataSource,
dataBound: function () {
DisplayNoResultsFound($('#grid'));
},
The javascript function 'DisplayNoResultsFound' is as follows
function DisplayNoResultsFound(grid) {
// Get the number of Columns in the grid
var dataSource = grid.data("kendoGrid").dataSource;
var colCount = grid.find('.k-grid-header colgroup > col').length;
// If there are no results place an indicator row
if (dataSource._view.length == 0) {
grid.find('.k-grid-content tbody')
.append('<tr class="kendo-data-row"><td colspan="' + colCount + '" style="text-align:center"><b>No Results Found!</b></td></tr>');
}
// Get visible row count
var rowCount = grid.find('.k-grid-content tbody tr').length;
// If the row count is less that the page size add in the number of missing rows
if (rowCount < dataSource._take) {
var addRows = dataSource._take - rowCount;
for (var i = 0; i < addRows; i++) {
grid.find('.k-grid-content tbody').append('<tr class="kendo-data-row"><td> </td></tr>');
}
}
}
First, you should add a name to your kendo instance(myList):
<kendo-mobile-list-view="myList" id="myList" class="item-list" k-template="templates.myListTemp" k-data-source="myService.myDataSource">
</kendo-mobile-list-view>
Then, in your controller:
$scope.myList.bind('dataBound',DisplayNoResultsFound)
Also you could specify some k-options in the html and read those options(including the dataBound) from the angular controller, this link explains more about it

Populate and display an html table based on the values from two dropdown menus

I have two cascading dropdown boxes controlled with JQuery and Ajax objects. The first determines the values in the second. Then, once a selection is made in the second, the values from the two dropdowns would be used to find a record in an SQL table and display the record in an html table.
So far the dropdowns work correctly but I'm having difficulty getting the record from the database and then displaying it on screen. I've done this before by getting the database values, sending them to the view in a Json object, and using an Ajax object to to create the table with Jquery. However, in this case I don't mind if the page reloads and would like to use a simpler method.
What is a simple method of sending two values from two dropdowns to the controller, using those values to find a record in an sql table, sending the values from the record back to the view to be displayed? Also, I don't want anything to be displayed until the second dropdown box has a selection made.
Here is what I have so far:
Controller methods:
List<Car> GetCars()
{
using (var service = new Service())
{
return service.GetCars().OrderBy(x => x.CarName).Select(x => new Car
{
CarId = x.CarId,
CarName = x.CarName
}).ToList();
}
}
List<Color> GetColors(int carId)
{
using (var service = new Services())
{
return service.GetColors(carId).OrderBy(x => x.ColorName).Select(x => new Color
{
ColorId = x.ColorId,
ColorName = x.ColorName
}).ToList();
}
}
[HttpPost]
public ActionResult CurrentSaus(int townCode, int fiscalYear)
{
var colors = GetColors(carId);
return Json(new SelectList(colors, "ColorId", "ColorName"));
}
Jquery methods:
$(document).ready(function () {
$("#Car_CarId").change(function () {
var carId = $(this).val();
var carName = $(":selected", this).text();
// put the car name into a hidden field to be sent to the controller
document.getElementById("Car_CarName").value = carName;
getColors(carId);
})
});
function getColors(carId) {
if (carCode == "") {
$("#Color_ColorId").empty().append('<option value="">-- select color --</option>');
}
else {
$.ajax({
url: "#Url.Action("Colors", "HotWheels")",
data: { colorId: clrId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred");
},
success: function (data) {
var colors = "";
var numberOfColors = data.length;
if (numberOfColors > 1) {
colors += '<option value="">-- select color --</option>';
}
else {
var colorId = data[0].Value;
var colorName = data[0].Text;
document.getElementById("Color_ColorName").value = colorName;
}
$.each(data, function (i, color) {
colors += '<option value="' + color.Value + '">' + color.Text + '</option>';
});
$("#Color_ColorId").empty().append(colors);
}
});
}
and some of the html:
#Html.HiddenFor(x => x.Car.CarName)
#Html.HiddenFor(x => x.Color.ColorName)
<table>
<tr>
<td> Select Car:</td>
<td style="text-align:left">
#Html.DropDownListFor(
x => x.Car.CarId,
new SelectList(Model.CarList, "CarId", "CarName"),
"-- select town --")
<br />
#Html.ValidationMessageFor(x => x.Car.CarId)
</td>
</tr>
<tr>
<td> Select Color:</td>
<td colspan="4">
#Html.DropDownListFor(
x => x.Color.ColorId,
new SelectList(Model.ColorList, "ColorId", "ColorName"),
"-- select color --")
<br />
#Html.ValidationMessageFor(x => x.Color.ColorId)
</td>
</tr>
</table>
}
The easiest method is to use an old fashion FORM element and POST the values of the two drop downs to an action in your controller. That action would expect a carId and a colorId and use them to retrieve a record from the DB and then pass the result to your 'view' where you would take care of render/display the result.
Of course using this method has some caveats:
The entire page will refresh after a user selects a value from the
second drop down.
You would have to POST the form using JavaScript
when the user picks the second option, or at least enable a button so
the form can be POSTed.
You would have to keep track of the carId and
colorId in your controller and view
Another option is to use AJAX to POST (send to the server) the carId and colorId where and action in a controller will take care of using those parameters to find a record in the DB and then return a JSON object with the result. The response will be handled by a 'success' handler where you will take care parsing the JSON object and add rows to a table.
So if you feel more comfortable working on the server side of the code pick the first option, however if you prefer to use AJAX and do this in the front end use the later.

Angular JS : creating table with json

I've created an application in angular-JS for creating table with dynamic columns from json
For example the JSON structure returning from a service is in the structure where the others field of the main JSON contains another JSON array which is the additional columns,
so all together there will be four additional dynamic columns i.e File 1, File 2, File 3, File 4 each object has value for the corresponding File field, sometime present sometime not present.
$scope.getColumns = function()
{
//console.log( $scope.datas[0].others[0]);
$scope.datas.resultsOrder = new Array();
for ( var i = 0; i < $scope.datas.length; i++)
{
for ( var j = 0; j < $scope.datas[i].others.length; j++)
{
if (countInstances($scope.datas.resultsOrder, $scope.datas[i].others[j].id) < countInstances(
$scope.datas[i].others, $scope.datas[i].others[j].id)){
$scope.datas.resultsOrder.push($scope.datas[i].others[j].id);
}
}
}
$scope.datas.resultsOrder.sort(function(a, b){
return a.localeCompare(b);
});
return $scope.datas.resultsOrder;
}
I've shown the tables with the dynamic columns perfectly using javascript help, but can anyone please tell me some other way for creating the above dynamic table through angular js in a simple way, since in my code I've used javascript complex logic for the creation of dynamic columns which is as shown below
My JS-Fiddle is given below
Demo
This wll create an object called columns where the properties are the names of the dynamic columns ('File 1', 'File 2' etc.)
Controller:
$scope.columns = {};
angular.forEach( $scope.datas, function(data){
angular.forEach( data.others, function(other){
// Set the 'File x' property for each item in the others array
data[other.id] = other.value;
// Add the dyanmic column to the columns object
$scope.columns[other.id] = null;
});
});
View:
<!-- table header -->
<tr>
<th ng-repeat="(column,val) in columns">
<a ng-click="sort_by()"><i>{{column}}</i></a>
</th>
....
</tr>
<!-- data rows -->
<td ng-repeat="(column,v) in columns">{{val[column]}}</td>
Fiddle

Categories

Resources