Selecting rows from one grid & passing them to another grid - javascript

I'm trying to allow rows to be selected via checkboxes and for those selected rows and their IDs to be sent to another grid when a 'Submit' button is clicked. In other words, acting as some sort of filter.
I've contacted Telerik's support team and was advised to take the following steps in order to get it working:
Get the selected rows with the Select() method of the Grid
Loop through them & get the underlying item with the dataItem method
Save them into an array
Destroy the grid
Initialize a new grid by setting the data data
Here's a sample on JSBin that shows what I have in mind.
I'm not sure where to start honestly. I would really appreciate it if someone could point me in the right direction to any resources or guides that would be helpful. Thanks!

Assuming you are using RadGrid, make sure you have client side selection turned on, you would see something like this:
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowSelected="RowSelected" />
</ClientSettings>
On the input button, make sure to call your JS method as follows :
<input onclick="GetSelected();" .... >
Your JS code might look something like this :
function GetSelected() {
var grid = $find("<%=Your Grid's ClientID Here%>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems(); // 1. Get the selected rows. The selected item can be accessed by calling the get_selectedItems() method of the GridTableView client-side object.
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
// This is where you would have to insert it in a collection so that you can bind it to another grid... You will need to call .Rebind() once you assign the new datasource to the other grid.
}
Hopefully this will give you some idea.. I can see if I can find any examples on inserting rows into other grid if you get stuck.

check this code
html
<div id="grid1"></div>
<input type="button" value="Submit" onclick="Move()" />
<div id="grid2" ></div>
script
<script>
$(document).ready(function() {
var data1 = [
{ id: 1, rating: 3, year: 1997, title: "Rock" }
, { id: 2, rating: 5, year: 1999, title: "X-Man" }
, { id: 3, rating: 4, year: 2011, title: "World War Z" }
];
var grid1=$("#grid1").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ template: "<input type='checkbox' class='checkbox' />", width: "40px" }
,{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data1
}
}).data("kendoGrid");
grid1.table.on("click", ".checkbox", selectRow);
var data2 = [
{ id: 101, rating: 6, year: 2012, title: "The Impossible" }
, { id: 102, rating: 8, year: 2013, title: "Escape" }
, { id: 103, rating: 7, year: 2013, title: "Gravity" }
];
$("#grid2").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data2
}
});
});
function Move() {
var grid1 = $("#grid1").data("kendoGrid");
var rows = grid1.select();
rows.each(function(index, row) {
var selectedRow = grid1.dataItem(row);
//-move to grid2
var grid2 = $("#grid2").data("kendoGrid");
var ins = { id: selectedRow.id, rating: selectedRow.rating, year: selectedRow.year, title: selectedRow.title }; //id=1,rating=9.2,year=1995,title="The Godfather"
grid2.dataSource.insert(ins);
});
rows.each(function() {
grid1.removeRow($(this).closest('tr'));
});
}
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr");
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
</script>
this will help you :)

Related

Getting the selected items count in a kendoMultiSelect footerTemplate

Is it possible to get the selected items count in the kendoMultiSelect's footerTemplate?
I created a DOJO example with an attemp to use instance.dataItems().length but for some reason, the value is always 0.
$("#customers").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
footerTemplate: '#: instance.dataItems().length # item(s) selected'
});
EDIT:
due #Aleksandar comment where he points out
Calling setOptions in an event handler or the respective widget is not
recommended and can cause an endless loop or a JavaScript error.
I take his suggestion into account and add his solution as an answer.
footerTemplate: '<span id="total">#:instance.value().length#</span> item(s) selected',
change:function(e){
var itmsSelected = e.sender.value().length;
$("#total").html(itmsSelected);
}
OBSOLETE:
Guess it's not in an observable object. One of the possible solutions is to change footerTemplate
every time a change happens on multiSelect:
var multi = $("#customers").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
change: function() {
this.setOptions({"footerTemplate": this.value().length +" item(s) selected"});
},
dataTextField: "name",
dataValueField: "id",
footerTemplate: '0 item(s) selected'
}).getKendoMultiSelect();
Example: Footer template update

How can you get Tabulator to use Select2 header filter?

Following the example here, we've been trying for over a week to get Tabulator working with a Select2 header filter. There is a JS Fiddle here with all the pieces. It seems like the Tabulator filter (which are really just editors) onRendered() function is not even getting called because the console log we have inside it never gets logged.
The select element itself shows up in the header filter, but never gets the Select2 object applied (probably because the onRendered seems to not even be called). If we put the Select2 object outside the onRendered function, it get applied, but then the filter does not get applied after selection is made. There are no console or other errors and we've followed the Tabulator 'example' to the letter, so we are not sure what to try next.
Does anyone know how to get a basic Select2 header filter functioning with Tabulator?
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var select2Editor = function(cell, onRendered, success, cancel, editorParams) {
var editor = document.createElement("select");
var selData = [{
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
onRendered(function() {
// TODO: map tracks to id and text
console.log('rendered');
$(editor).select2({
data: selData,
minimumResultsForSearch: Infinity,
width: '100%',
minimumInputLength: 0,
//allowClear: true,
});
$(editor).on('change', function(e) {
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
});
return editor
};
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: select2Editor,
}, ];
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
});
I'm new to both Tabulator and select2 and I think this is possibly a bad way to do it but it seems like it miiight work.
If you want to use select2 with text input elements, it looks like you need to use the full package.
https://jsfiddle.net/dku41pjy/
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: 'select2Editor'
}, ];
var awaiting_render = [];
function do_render({ editor, cell, success, cancel, editorParams }) {
console.log('possibly dodgy onrender');
var selData = [{
id: '',
text: "-- All Topics --"
}, {
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
$(editor).select2({
data: selData,
//allowClear: true,
});
$(editor).on('change', function(e) {
console.log('chaaaange')
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
}
function render_awaiting() {
var to_render = awaiting_render.shift();
do_render(to_render);
if(awaiting_render.length > 0)
render_awaiting();
}
Tabulator.prototype.extendModule("edit", "editors", {
select2Editor:function(cell, onRendered, success, cancel, editorParams) {
console.log(cell);
var editor = document.createElement("input");
editor.type = 'text';
awaiting_render.push({ editor, cell, success, cancel, editorParams });
return editor
},
});
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
tableBuilt:function(){
render_awaiting();
},
});
Edit: my suspicion is that onRendered only gets fired when these edit elements are used in cells to sope with the transition between showing just data and showing an editable field.

Slick Grid - formatters.delete not showing in the grid when adding values by input type text

I have a grid with two columns: name and delete. When the user enters to an input text a value and clicks the button, that value is added to the grid. The problem is that the column "Delete" doesn't work,the column "Delete" doesn't display anything. See the code below:
grid = new Slick.Grid("#mygrid", gridData.Selections, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
$("#btnAddValue").click(function () {
var newItem = { "SelectionName": $("#Name").val() };
$('#pickListName').val('');
var item = newItem;
data = grid.getData();
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
var columns = [
{ id: "SelectionName", name: "Name", field: "SelectionName", width: 420, cssClass: "cell-title", validator: requiredFieldValidator },
{ id: "Id", name: "Delete", field: "Id", width: 80, resizable: false, formatter: Slick.Formatters.Delete }];
var options = {
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true};
How should solve this?
Thank you

Display image along with text in a cell when in non-edit mode

I'm evaluating the Kendo UI Gantt chart to see if it fits our project requirements.
One particular requirement is to display a status column which would be a drop down in edit mode and has three statuses
Red 2. Green 3. Yellow, along with an image indicator something like what is shown in the image below
I am able to achieve the above effect when i edit a cell after using a custom editor for the drop down
function statusDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Status",
dataValueField: "StatusId",
valueTemplate: '<img class="selected-value" src="#:data.Url#" alt="#:data.Status#" /><span>#:data.Status#</span>',
template: '<img class="selected-value" src="#:data.Url#" alt="#:data.Status#" /><span>#:data.Status#</span>',
dataSource: {
transport: {
read: function (e) {
// on success
e.success([{ Status: 'Not Started', StatusId: '0', Url: 'Image/red.png' }, { Status: 'Red', StatusId: '1', Url: 'Image/red.png' }, { Status: 'Green', StatusId: '2', Url: 'Image/red.png' }, { Status: 'Yellow', StatusId: '3', Url: 'Image/red.png' }]);
// on failure
//e.error("XHR response", "status code", "error message");
}
}
}
})
}
The Gantt Column for Status looks like the below snippet
{ field: "status", title: "Status", editable: true, width: 150, editor: statusDropDownEditor, template: '<img class="selected-value" src="#:data.Url#" alt="#:data.Status#" /><span>#:data.Status#</span>' }
However when done with selecting a particular item from drop down and on exiting the edit mode this is how the cell looks like
Seems like the default cell template in read only mode does not render html and the invokes the toString of the object bound to the cell, is there a way to fix this in the kendo UI Gantt
I have been trying to solve the same issue today and it looks like gantt columns do not support the template properties.
I have created a new feature suggestion on the Kendo user feedback site. If enough people vote for it maybe they will implement this.
The only work around I found was to prepend an image tag onto the field column like this. But this solution is not conditional.
<div id="gantt"></div>
<script>
$(document).ready(function() {
var gantt = $("#gantt").kendoGantt({
dataSource: [
{
id: 1,
title: "apples",
orderId: 0,
parentId: null,
start: new Date("2015/1/17"),
end: new Date("2015/10/17"),
summary:false,
expanded:false
},
{
id: 2,
orderId: 1,
parentId: null,
title: "banana",
start: new Date("2015/1/17"),
end: new Date("2015/3/17"),
summary:false,
expanded:true
}
],
views: [
{ type: "year", selected: true }
],
columns: [
{ field: "title", title: "fruit", width: 220 },
{ field: "start", title: "start", width: 80 }
],
}).data("kendoGantt");
$(".k-grid-content tbody[role='rowgroup'] tr[role='row'] td:first-child").prepend("<img href='#' alt='image here'></img>");
});
</script>
The sample page is on git.

EnhancedGrid within another EnhancedGrid

I'm using the dojo grid cell formatter to display an inner grid within another grid. Even though the inner grid is added, it does not display on the HTML page cause its height and width are 0px.
My JSP page and the JS page where the grids are created is shown below. Any help will be appreciated.
My guess is that calling grid.startup() in the cell formatter is probably not the right place. But where should I move the startup() call to -or- is there something else that needs to be done to get the inner grid to render correctly.
----JSP file ----
<script type="text/javascript"> dojo.require("portlets.ListPortlet"); var <portlet:namespace/>args = { namespace: '<portlet:namespace/>', listDivId: 'listGrid' }; var <portlet:namespace/>controller = new portlets.ListPortlet(<portlet:namespace/>args); dojo.addOnLoad(function(){ <portlet:namespace/>controller.init(); }); </script>
</div>
----JS file ----
dojo.declare("portlets.ListPortlet", null, {
constructor: function(args){
dojo.mixin(this,args);
this.params = args;
},
init: function(){
var layout = [[
{field: 'site', name: 'Site', width: '30px' }
{field: 'name', name: 'Full Name', width: '100px'},
{field: 'recordStatus', name: 'Status', width: '80px' }
],[
{field: '_item', name: ' ', filterable: false, formatter: this.formatNotesTable, colSpan: 3 }
]];
this.grid = new dojox.grid.EnhancedGrid({
autoHeight: true,
autoWidth: true,
selectable: true,
query:{
fromDate: start,
toDate: end
},
rowsPerPage: 10
});
this.grid.placeAt(dojo.byId(this.listDivId));
this.dataStore = new dojox.data.JsonRestStore({target: dataURL, idAttribute: idAttribute});
this.grid.setStructure(layout);
this.grid.startup();
},
formatNotesTable(rowObj) {
var gridData = {
identifier:"id",
items: [
{id:1, "Name":915,"IpAddress":6},
{id:2, "Name":916,"IpAddress":7}
]
};
var gridStructure = [{
cells:[
[
{ field: "Name",
name: "Name",
},
{ field: "IpAddress",
name: "Ip Address" ,
styles: 'text-align: right;'
}
]
]
}];
var gridStore = new dojo.data.ItemFileReadStore( { data: gridData} );
var cpane = new dijit.layout.ContentPane ({
content: "inner grid should be displayed below"
});
var subgrid = new dojox.grid.DataGrid({
store: gridStore,
structure: gridStructure,
style: {width: "325px", height: "300px"}
});
subgrid.placeAt(cpane);
subgrid.startup();
return cpane;
}
}
I solved my problem by using a dojox.layout.TableContainer inside the EnhancedGrid.

Categories

Resources