populating input field with row data when row is clicked on - javascript

How can i populate form inputs with the row data of a row that is clicked on? (using AG GRID and vanilla JS)
Example code would be appreciated
const gridOptions = {
columnDefs: [
{field: "make", sortable: true, filter: true},
{field: "model", sortable: true, filter: true},
{field: "price", sortable: true, filter: true}
],
rowData: [
{make: "VW", model: "Jetta", price: "$25,000"},
{make: "Honda", model: "Odyssey", price: "$35,000"},
{make: "Audi", model: "Q2", price: "$45,000"}
],
animateRows: true,
onCellClicked: params => {
let dataMake = params.data.make;
console.log(dataMake);
const fillInput = (e) => {
e.preventDefault()
const input1 = document.querySelector("#input1").value
console.log(input1);
input1 = "dataMake"
}
}
};
new agGrid.Grid(eGridDiv, gridOptions)
fetch("https://www.ag-grid.com/example-assets/row-data.json")
.then(res => res.json())
.then(data => {
gridOptions.api.setRowData(data)
});

I'm assuming that you know how to set values in your form, and that you're just asking how to get the data from the grid.
So, if I understand correctly, you're asking about filling in multiple form fields, corresponding to multiple cells in grid row, when the row is clicked.
Your code looks correct except that you are using the onCellClicked property where you should be using onRowClicked.
With onCellClicked the param to the callback is the data backing the cell that was clicked, while with onRowClicked the param is the object backing the entire row.

Related

Add unique id to every row using ag-Grid

I used the ag-Grid plugin in javascript for my grid. My problem is figuring out how I can update the rows into database. How can I set a unique id to every row?
<div id="myGrid" style="height: 600px;" class="ag-theme-balham"></div>
<script type="text/javascript" charset="utf-8">
// specify the columns
var columnDefs = [
{headerName: "Make", field: "make"},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"}
];
// specify the data
var rowData = [
{make: "Toyota", model: "Celica", price: 'test', my_unique_id: '123'},
{make: "Ford", model: "Mondeo", price: 32000, my_unique_id: '42341'},
{make: "Porsche", model: "Boxter", price: 72000, my_unique_id: '567'}
];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData
};
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(eGridDiv, gridOptions);
</script>
On the definition of your columns columnDefs you need to add the key and, if you need, set hide: true to this data not appears on UI
var columnDefs = [
{headerName: "Make", field: "make"},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"},
{headerName: "Key", field: "my_unique_id", hide = true},
];
See all properties for columns on ag-grid docs here: https://www.ag-grid.com/javascript-grid-column-properties/
I am not sure if you are aware of this, but ag-grid actually assigns a unique ID to every row, when the row data is set.
On of the ways to access the id for each row node would be to use the forEachNode() method, as specified within the ag-grid gridOptions API documentation. forEachNode() iterates all rows, and returns the data for each row.
Assuming you are using Vanilla JavaScript (without any frameworks such as React or Angular), you do the following to get the id
gridOptions.api.forEachNode(node => {
console.log(node.id);
// do the rest
});
{
headerName: "Num",
field: "id",
filter: true,
width: 150,
cellRendererFramework:(params)=>{
return <span>{params.rowIndex}</span>
}
},

Agroup data using ag-grid

I am currently using ag-grid in my project. Am trying to agroup the data using the agrouping feature.
In my col def I have this:
{headerName: "Parent", field: "ParentID",width: 120,rowGroup:true},
{headerName: "Name", field: "Name"},
{headerName: "Level", field: "Level"},
{headerName: "Active", field: "Active"},
{headerName: "Actions",
field: "Actions",
cellRenderer: function (params) {
/*Generate a link and return it*/
return EditLink;
}
}
Then, the ag-grid options:
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
onGridReady: function () {
gridOptions.api.sizeColumnsToFit();
},
animateRows: true,
enableRangeSelection: true,
enableSorting: true,
enableFilter: true,
enableColResize: true,
domLayout:'autoHeight',
rowHeight: 48,
enableStatusBar: true,
rowSelection: 'single',
groupMultiAutoColumn:true,
groupRemoveSingleChildren:true,
icons: {
checkboxChecked: '<img src="data:image/png;base64,SOMECODEHERE"/>'
}
};
However, I am not getting the expected behaviour, I have the table rendered with the data and the column to agroup the data, but it's not agrouped, it's like ordered but I don't see the button to dropdown the children
Are you sure the ParentID is shared amongst several rows? The groupRemoveSingleChildren option will show no groups if no ids are shared.
You can also try using rowGroupIndex as opposed to rowGroup
i.e
this.columnDefs = [
{headerName: "Clan", field: "clan", editable: true, rowGroupIndex: 0 },
The rowGroupIndex allows sub groups to be defined so you can nest groups (if you need to).
I would also recommend removing the groupRemoveSingleChildren just to see if you get the checkbox or whether the data is at fault..

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

Selecting rows from one grid & passing them to another grid

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 :)

How do put the JSON into EXTJS Grid?

I have a search with 3 Comboboxes if they are selected, the selected valueid send them by $POST and then by AJAX to PHP.
PHP is building from the combobox id's a mysql query and sends it back as JSON.
(JSON is validated)
But my grid is not filled! how i put the filtered by id data in my grid?
My Button
buttons:[
{
text:'Search',
loadingText:'lädt',
handler:function () {
var form = Ext.getCmp('searchPanel').getForm();
form.submit(
{url: 'php/search.php'}
)
MY validated JSON
"getRoutedata": [
{
"RouteID": "3",
"Loadingpoint": "Hafencity",
"Postalcode": "20457",
"Containercity": "Uhlenhorst",
"Carrier": "Bre SO",
"Transportmodel": "Truck",
"Containersize": "40",
"Containertype": "Horizontal",
"Harbor": "Antwerpen",
"Price": "1000.00",
"Year": "2012",
"Misc": "test"
}
]
My Store
storePPT = new Ext.data.JsonStore({
url:'php/search.php',
storeId:'myStore',
root:'getRoutedata',
stateful:true,
idProperty:'RouteID',
fields:[
{name:'Carrier', type:'string', mapping:'Carrier'},
{name:'Containercity', type:'string', mapping:'Containercity'},
{name:'Containersize', type:'string', mapping:'Containersize'},
{name:'Containertype', type:'string', mapping:'Containertype'},
{name:'Harbor', type:'string', mapping:'Harbor'},
{name:'Loadingpoint', type:'string', mapping:'Loadingpoint'},
{name:'Misc', type:'string', mapping:'Misc'},
{name:'Postalcode', type:'string', mapping:'Postalcode'},
{name:'Price', type:'decimal', mapping:'Price'},
{name:'Transportmodel', type:'string', mapping:'Transportmodel'},
{name:'Year', type:'year', mapping:'Year'},
{name:'RouteID', type:'int', mapping:'RouteID'}
]
});
Big thanks for your help!
You need to have store that will hold parsed data from your JSON response and a grid that will display data from this store. like:
//call this function in ajax success
function loadJsonData() {
var myStore = Ext.create('Ext.data.JSONStore', {
fields: [
{name1: 'field_name1'},
{name2: 'field_name2'},
{name3: 'field_name3'}
],
data: jsonData
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: myStore,
stateful: true,
stateId: 'stateGrid',
columns: [ {
text : 'field_name1',
sortable : false,
dataIndex: 'field_name1' // add fields you want to display
}, ... ]
renderTo: 'table' // add other params as you want
});
};
Hope it helps

Categories

Resources