Kendo Chart with simple dynamic grid - javascript

I have a chart with date and count, avg, min, max functions. When I click functions I can get all values of my chart.
I just want to show a simple grid near my chart. I just want to show my categories name and their values. I have been trying for hours but I couldn't do that.
I can show my categories name with this code:
$("#ce").html(series[3].name);
And I want to show its value near it.
But I can't. Thanks for your help.
Here is an example of what I mean with JavaScript functions:
Telerik Kendo chart with date functions
Here is my code:
<td>
<div align="center" id="aa">
#(Html.Kendo().Chart(Model)
.Name("chartMesleki258")
.Title(title => title
.Text("aa)")
.Position(ChartTitlePosition.Top))
.Legend(legend => legend
.Visible(true)
.Position(ChartLegendPosition.Top))
.Series(series =>
{
series
.Column(model => model.aa, categoryExpression: model => model.EvrakTarih).Name("eee Dosyalar")
.Aggregate(ChartSeriesAggregate.Count);
series
.Column(model => model.aa, categoryExpression: model => model.EvrakTarih).Name("eee Dosyalar")
.Aggregate(ChartSeriesAggregate.Count);
series
.Column(model => model.aa, categoryExpression: model => model.EvrakTarih).Name("Kapsam Disi Dosyalar")
.Aggregate(ChartSeriesAggregate.Count);
})
.CategoryAxis(axis => axis
.Date()
.BaseUnit(ChartAxisBaseUnit.Months)
.MajorGridLines(lines => lines.Visible(false)))
.Tooltip(tooltip => tooltip
.Visible(true)
.Template("#= series.name #: #= value #"))
)
</div>
</td>
<script>
$(document).ready(function () {
$(".configuration").bind("change", refresh);
});
function refresh() {
var chart = $("#chartMesleki258").data("kendoChart"),
series = chart.options.series,
type = $("input[name=seriesType]:checked").val(),
stack = $("#stack").prop("checked");
for (var i = 0, length = series.length; i < length; i++) {
series[i].stack = stack;
series[i].type = type;
};
chart.refresh();
}
</script>
<script type="text/javascript">
$(".configuration").bind("change", refresh);
function refresh() {
var chart = $("#chartMesleki258").data("kendoChart"),
series = chart.options.series,
categoryAxis = chart.options.categoryAxis,
baseUnitInputs = $("input:radio[name=baseUnit]"),
aggregateInputs = $("input:radio[name=aggregate]");
for (var i = 0, length = series.length; i < length; i++) {
series[i].aggregate = aggregateInputs.filter(":checked").val();
}
categoryAxis.baseUnit = baseUnitInputs.filter(":checked").val();
chart.refresh();
}
</script>

Related

Get Elements of a HTML div

i am building a configuration utility and having a problem with the js.
I am very new to javascript so i apologize in advance for the request for help.
in my HTML i have multiple divs that are structured like this:
<div id="options" class="opt">
<h2 id="optionName">Power Button Options</h2>
<label for="pwrAvl">Power Button Available</label>
<input type="checkbox" name="pwrAvl" id="pwrAvl"/ >
<br /><br />
<label for="pwrLabel">Power Button Label</label>
<input type="text" name="pwrLabel" id="pwrLabel"/ >
<br /><br />
<label for="pwrGraphic">Power Button Graphic</label>
<select name="pwrGraphic" id="pwrGraphic">
<option value="" selected>
----- Please select a graphic -----
</option>
<option value="power.jpeg">Power</option>
<option value="light.jpg">Light</option>
<option value="help.jpg">Help</option>
<option value="camera.jpg">Camera</option>
</select>
<br /><br />
<label for="pwrIndex">Power Button Menu Index</label>
<input type="text" name="pwrIndex" id="pwrIndex"/ >
</div>
i have between 5-10 divs that will all be structured the same way just with different labels and input values.
i tried adding all the divs to an array and then enumerate through the array but that did not work.
here is my js file what i have tried:
{
const bar = document.querySelector('options');
var opts = document.querySelectorAll('.opt')
var option = {}
var nCount = $(".opt").length;
var divArray = [];
var optName = document.getElementById('optionName');
function addArray() {
for (let i = 0; i < nCount; i++) {
divArray[i] = opts[i];
}
}
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration": {
"Options": [],
}
}
addArray()
console.log(`Divarray = ${divArray.length}`)
//The following would never work
opts.forEach(label => {
$('[id=optionName]').each(function () {
var atId = this.id;
console.log(`Searched Name = ${atId.innerHTML}`)
});
});
divArray.forEach(element => {
var name = divArray.getElementById('optionName').innerHTML;
console.log(name)
option = new SystemOptions(name, "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
});
for (let i = 0; i < nCount; i++) {
// console.log(` ${$(".opt").find("h2[id=optionName").each.text()}`)
console.log(` ${divArray[i].querySelector(optName[i]).innerHTML}`)
}
// i did this once to see if the SystemsOptions function worked
// obviosly it added the same data 7 times but i was trying to be sure the function worked and created the json objects
for (let i = 1; i < nCount; i++) {
option = new SystemOptions("Power", "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
}
let data = JSON.stringify(info, 0, 4);
console.log(data);
}
}
any help would be greatly appreciated.
not the most eloquent but this does work.
sure there are better ways:
var opts = document.querySelectorAll('.opt');
var option = {};
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration" :{
"Options": [],
}
};
for(var opt of opts)
{
var name = opt.getElementsByTagName('h2')[0].innerHTML;
let isAvailable = opt.getElementsByTagName("input")[0].value;
let optLabel = opt.getElementsByTagName("input")[1].value;
let optGraphic = opt.getElementsByTagName('select')[0].value;
let index = opt.getElementsByTagName("input")[2].value;
option = new SystemOptions(name, isAvailable, optLabel, optGraphic, index);
info.SystemConfiguration.Options.push(option);
}
console.log(`Number of options = ${opts.length}`)
let data = JSON.stringify(info, 0, 4);
console.log(data);
};

Dynamically display sales tax when I select a state?

I am a student working on an assignment. The assignment is to
create an array that lists states
create a parallel array that lists state taxes
use JS to dynamically load the lists of states into the drop down menu
create a function that will display the tax rate using parallel state array...they want us to use a loop
I am stuck on the final part where I create a function using loops that will display the sales tax. My code is below.
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(){
for(x=0; x < states.length; x++){
document.getElementById("displayTaxPercent").innerHTML = salesTax[x];
}
}
When I do this I just get 8% over and over again.
The reason you are getting value as 8% is because you are not giving the selected value and code is simply iterating through all values and hence it will always show last value.
Here is simple example
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(state){
console.log(state + " : " + salesTax[states.indexOf(state)])
//document.getElementById("displayTaxPercent").innerHTML = salesTax[states.indexOf(state)];
}
displayTax("state1");
displayTax("state3");
const stateSelect = document.querySelector("#stateSelect");
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
stateSelect.append(
...states.map((state, stateI) => {
const optionEl = document.createElement("option");
optionEl.value = stateI;
optionEl.innerText = state;
return optionEl;
})
);
const display = () => {
document.querySelector("#results").innerText =
"Sales tax in " +
states[stateSelect.value] +
" is " +
salesTax[stateSelect.value];
};
stateSelect.addEventListener("change", display);
display();
<select id="stateSelect">
</select>
<p id="results"></p>

Chartjs Line Chart flickers between old and new data when hovering

My problem is not making the chart, but when I input new values for the start freq and end freq, which are the first and last values of my x-axis array after calling getFreq(), the chart glitches when I hover, going back and forth between the old data and new data. Can anyone help me figure out how to delete the old data and make/update to a new chart where the chart doesn't flicker? My code is shown below.
let Conductivity = document.getElementById('Conductivity');
let StartFreq = document.getElementById('StartFreq');
let StopFreq = document.getElementById('StopFreq');
let a = document.getElementById('a');
let b = document.getElementById('b');
let unitInch = document.getElementById('unitInch');
let test = document.getElementById('test');
let diameter = document.getElementById('Diameter');
let ctx = document.getElementById('myChart').getContext('2d');
function generateLabels(){
// To generate the xa xis intervals
let xaxis = [];
for (let i = 0; i <= 10; i++) {
let valToAppend = Math.round((parseFloat(StartFreq.value) + (parseFloat(StopFreq.value)-parseFloat(StartFreq.value)) / 10 * i)*100)/100;
if (valToAppend <= parseFloat(StopFreq.value)){
xaxis.push(valToAppend)
}
}
return xaxis
}
function getFreq(){
let x = generateLabels();
let freq = [];
let start = x[0];
freq.push(start);
let end = x[x.length - 1];
for (let i=0; i < 4 * (end-start);i++){
let lastfreq = freq[freq.length - 1];
freq.push(lastfreq + 0.25)
}
// let rklen = freq.length;
return freq
}
function getRS(){
let RS = [];
let freq = getFreq();
freq.forEach(element =>{
let RStoAppend = Math.sqrt((2*Math.PI*(Math.pow(10,9)*element)*(4*Math.PI*Math.pow(10,-7)))/(2*(parseFloat(Conductivity.value)*Math.pow(10,7)))) ;
RS.push(RStoAppend)
});
return RS
}
function getRK(){
let RK = [];
let freq = getFreq();
freq.forEach(element => {
let RKtoappend = (2*Math.PI*(element * Math.pow(10,9))) / (3* Math.pow(10,8));
RK.push(RKtoappend)
});
return RK
}
function getRbeta(){
let Rbeta = [];
let RK = getRK();
RK.forEach(element => {
let Rbetatoappend = Math.sqrt(Math.pow(element,2) - Math.pow((Math.PI/(parseFloat(a.value)*25.4/1000)),2));
Rbeta.push(Rbetatoappend);
});
return Rbeta;
}
function getRatte(){
let Ratte = [];
let RS = getRS();
let RK = getRK();
let Rbeta = getRbeta();
for (let i = 0; i < RS.length ;i++){
let Rattetoappend = RS[i]*(2*(25.4/1000*parseFloat(b.value))*Math.pow(Math.PI,2)+Math.pow((parseFloat(a.value)*25.4/1000),3)*Math.pow(RK[i],2))/(Math.pow((parseFloat(a.value)*25.4/1000),3)*(25.4/1000*parseFloat(b.value))*Rbeta[i]*RK[i]*377)/(1000/25.4);
Ratte.push(Rattetoappend);
}
// test.innerHTML = '<td id="test">' + Ratte + '<td>';
return Ratte
}
function getRTE10(){
let RTE10 = [];
let Ratte = getRatte();
Ratte.forEach(element => {
if (isNaN(-20*Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))) {
RTE10.push(0)
}
else {
RTE10.push(-20 * Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))
}
});
return RTE10
}
//////////////////////// For CTE11/////////////
function getk(){
let k = [];
let freq = getFreq();
freq.forEach(element => {
k.push(2*Math.PI*element*Math.pow(10,9)/(3*Math.pow(10,8)))
});
return k
}
function getbeta(){
let beta = [];
let k = getk();
k.forEach(element => {
beta.push(Math.sqrt(Math.pow(element,2)-Math.pow((1.8412/(parseFloat(diameter.value)/2*25.4/1000)),2)))
});
return beta
}
function getTE11_1(){
let TE11_1 = [];
let k = getk();
let rs = getRS();
let beta = getbeta();
for (let i = 0; i < rs.length ;i++){
TE11_1.push(rs[i]*(Math.pow((1.8412/(parseFloat(diameter.value)/2*25.4/1000)),2)+Math.pow(k[i],2)/(Math.pow(1.8414,2)-1))/((parseFloat(diameter.value)/2*25.4/1000)*k[i]*beta[i]*377)/(1000/25.4));
}
return TE11_1
}
function getCTE11(){
let CTE11 = [];
let TE11_1 = getTE11_1();
TE11_1.forEach(element => {
if (isNaN(-20 * Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))) {
CTE11.push(0)
}
else {
CTE11.push(-20 * Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))
}
});
// test.innerHTML = '<td id="test">' + CTE11 + '<td>';
return CTE11
}
function getTM01(){
let TM01 = [];
let rs = getRS();
let freq = getFreq();
for (let i = 0; i < rs.length ;i++){
TM01.push(rs[i]/((parseFloat(diameter.value)/2 *25.4/1000)*377*Math.sqrt(1-Math.pow(((2.4049/(2*Math.PI*parseFloat(diameter.value)/2 *25.4/1000)*0.3)*Math.pow(10,9)/(freq[i]*Math.pow(10,9))),2)))/(1000/25.4));
}
return TM01
}
function getCTM01(){
let CTM01 = [];
let TM01 = getTM01();
TM01.forEach(element => {
if (isNaN(-20 * Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))) {
CTM01.push(0)
}
else {
CTM01.push(-20 * Math.log10(Math.exp(-element)) * parseFloat(unitInch.value))
}
});
return CTM01
}
function getAt2(){
let at2 = [];
let freq = getFreq();
freq.forEach(element =>{
at2.push(Math.pow(((3.8318/(2*Math.PI*parseFloat(diameter.value)/2 *25.4/1000)*0.3)*Math.pow(10,9)/(element*Math.pow(10,9))),2)+1/(Math.pow(3.8318,2)-1))
});
return at2
}
function getAt1(){
let at1 = [];
let freq = getFreq();
let rs = getRS();
for (let i = 0; i < rs.length ;i++){
at1.push(rs[i]/(parseFloat(diameter.value)/2 *25.4/1000*377*Math.sqrt(1-Math.pow(((3.8318/(2*Math.PI*parseFloat(diameter.value)/2 *25.4/1000)*0.3)*Math.pow(10,9)/(freq[i]*Math.pow(10,9))),2)))/(1000/25.4));
}
return at1
}
function getCTE01(){
let CTE01 = [];
let at1 = getAt1();
let at2 = getAt2();
for(let i = 0;i < at1.length; i++){
if (isNaN((-20*Math.log10(Math.exp(-(at1[i]*at2[i])))*parseFloat(unitInch.value)))) {
CTE01.push(0)
}
else {
CTE01.push(-20 * Math.log10(Math.exp(-(at1[i] * at2[i]))) * parseFloat(unitInch.value))
}
}
return CTE01
}
function getdata(){
let data =[];
let xaxis = getFreq();
let RTE10 = getRTE10();
let CTE11 = getCTE11();
let CTM01 = getCTM01();
let CTE01 = getCTE01();
data.push(xaxis,RTE10,CTE11,CTM01,CTE01);
return data
}
function draw_chart(data) {
let chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: data[0],
datasets: [{
label: 'R-TE10',
data: data[1],
pointStyle : 'line',
backgroundColor: 'transparent',
borderColor: 'blue',
pointRadius: '0'
},{
label: 'C-TE11',
data: data[2],
pointStyle : 'line',
backgroundColor: 'transparent',
borderColor: 'orange',
pointRadius: '0'
},{
label: 'C-TM01',
data: data[3],
pointStyle : 'line',
backgroundColor: 'transparent',
borderColor: 'green',
pointRadius: '0'
},{
label: 'C-TE01',
data: data[4],
pointStyle : 'line',
backgroundColor: 'transparent',
borderColor: 'red',
pointRadius: '0'
}]
},
// Configuration options go here
options: {
responsive : true,
scales: {
xAxes :[{
ticks: {
min: StartFreq,
max: StopFreq,
suggestedMin: StartFreq,
suggestedMax: StopFreq,
stepSize: 0.25,
}
}],
yAxes: [{
ticks: {
min:0,
max:10,
suggestedMin: 0,
suggestedMax: 10,
maxTicksLimit: 11,
stepSize : 1,
beginAtZero: true,
}
}]
}
}
});
}
function generateChart() {
// removeData(chart);
let data = getdata();
draw_chart(data);
}
HTML
<table class="inner">
<tr class="inner">
<td class="inner"> Attenuation (air) /</td>
<td class="inner"> <input class="numInput" type="number" id="unitInch"/></td>
<td class="inner">(in inches)</td>
</tr>
<tr class="inner">
<td class="inner" colspan="2">Rectangular WG</td>
<td class="inner">Circular WG</td>
<td class="inner">Material</td>
</tr>
<tr class="inner">
<td class="inner">a (inch)</td>
<td class="inner">b (inch)</td>
<td class="inner">Diameter (inch)</td>
<td class="inner">Conductivity ( x 10<sup>7</sup> S/m)</td>
<td class="inner">Start Freq (GHz)</td>
<td class="inner">Stop Freq (GHz)</td>
</tr>
<tr class="inner">
<td class="inner"><input class="numInput" type="number" id='a'/></td>
<td class="inner"><input class="numInput" type="number" id="b"/></td>
<td class="inner"><input class="numInput" type="number" id="Diameter"/></td>
<td class="inner"><input class="numInput" type="number" id="Conductivity"/></td>
<td class="inner"><input class="numInput" type="number" id="StartFreq"/></td>
<td class="inner"><input class="numInput" type="number" id="StopFreq"/></td>
</tr>
</table>
<button onclick="generateChart()"><strong>Generate Chart</strong></button>
<div id="chartsize">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script src="js/chart.js"></script>
**By the way, my chart works completely fine the first time I load the page, then when I update, the chart flickers like crazy when hovering.
I added in a lot more code, so that you guys can recreate the chart and figure it out. Please ignore the bad style, I am new to Web Development...
**
This seems to be a somewhat common issue with Chart.js. The typical suggested solutions are to either destroy the chart instance, or remove the canvas element and create a new one whenever the chart is updated.
For the first possible solution, you can try calling destroy() on your chart object. For example, if your chart object is chart, you could call chart.destroy();. From the documentation:
Use this to destroy any chart instances that are created. This will
clean up any references stored to the chart object within Chart.js,
along with any associated event listeners attached by Chart.js. This
must be called before the canvas is reused for a new chart.
However, this doesn't seem to always work. Removing and creating the canvas element seemed to work when I tested it with your code. You could use a function like below and call it whenever you click the "Generate Chart" button:
function resetCanvas (){
$("canvas").remove();
$("#chartsize").append('<canvas id="myChart"><canvas>');
canvas = document.querySelector("#myChart");
ctx = canvas.getContext("2d");
};
Note that you might need to set the height and width of your chart container. I'm using jQuery for this function for simplicity. But you could reproduce it using vanilla JS if needed.
See the fiddle here for an example of this using your code: https://jsfiddle.net/fL1rd3wp/1/

HTML Input Form to a Javascript Variable

I'm trying to implement an HTML form input, of which will take the numerical value and convert it into a variable in Javascript. This will then be used with chartjs to plot an graph.
I have the graph fully functioning if I input the variable separately, as used in the code below. I have been trying to use a function to take the value from the HTML form.
var force = 10
var numberOfPointLoads = 1
var pointLoadLocation = 5
var beamLength = 10
var supportCondition = "simplySupported"
var split = beamLength //No. of Finite Elements
var splitArrayYAxis = Array.from({
length: (split + 1)
}, (x, i) => i);
var yAxis = splitArrayYAxis.map(x => (x * (beamLength / split)));
yAxis.push(pointLoadLocation)
yAxis.push(pointLoadLocation)
yAxis.sort(function(a, b) {
return a - b
});
var splitArrayXAxis = Array.from({
length: (split + 1)
}, (x, i) => i);
var xAxisEnd = splitArrayYAxis.map(x => (x * (beamLength / split)));
xAxisEnd.push(pointLoadLocation)
xAxisEnd.sort(function(a, b) {
return a - b
});
var xAxisStart = xAxisEnd.splice(0, (xAxisEnd.indexOf(pointLoadLocation) + 1));
xAxisEnd.unshift(pointLoadLocation);
var shearForce = force / 2
var xAxisStart = xAxisStart.map(x => (shearForce))
var xAxisEnd = xAxisEnd.map(x => (-shearForce))
var xAxis = xAxisStart.concat(xAxisEnd)
var data = yAxis.map((v, i) => ({
x: v,
y: xAxis[i]
}));
//chart is below this
new Chart(document.getElementById("shearPointLoad"), {
type: "scatter",
data: {
datasets: [{
label: "MyScatter",
lineTension: 0,
data: data
}]
},
options: {
stacked: false,
bezierCurve: false,
title: {
display: true,
text: 'Plot of the Scatter'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="shearPointLoad" width="400" height="250"></canvas> Force Input <input type="text" id="userInput"></input>
<button id="submitter">Submit</button>
<div id="output"></div>
The variable will be equal to the value of the HTML and will be reassigned when updated.
Thanks for any help.
EDIT
let someInput = document.getElementById('someInput')
function onButtonClick() {
let someVariable = parseFloat(someInput.value);
console.info(someVariable);
}
var force = "someVariable"
var numberOfPointLoads = 1
var pointLoadLocation = 5
var beamLength = 10
var supportCondition = "simplySupported"
var split = beamLength //No. of Finite Elements
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="shearPointLoad" width="400" height="250"></canvas>
<input id="someInput" type="number" <input/>
<button onclick="onButtonClick()">Click me</button>
Add onclick event to the button and define a function plotchart():
<button id="submitter" onclick="plotchart()">Submit</button>
Now, to read the input value in the function:
var data = document.getElementById("userInput").value;
Now, wrap all you chart plotting code inside plotchart() function.
You need to use the button event onclick, so every time you click it, you can then grab the input's value using a reference to the element. Like the following snippet:
let someInput = document.getElementById('someInput')
function onButtonClick() {
let someVariable = parseFloat(someInput.value);
console.info(someVariable);
}
<input id="someInput" type="number" />
<button onclick="onButtonClick()">Click me</button>
After this, you may use someVariable for anything you need.
Notes:
Use a type="number" input for better UX (so users can't input text or some other characters)
Consider resetting the input value after clicking the button.

How to persist selection checkbox state when paging or changing tab on the kendo grid

I want to persist selection of checkbox while paging or moving on other tab in kendo grid .I have referred "How to keep current checkbox state when paging on the grid" here and but i didn't get value of checked and checkbox and also confused with the steps.Please guide in detail.I have attached code below.I have attached script code kendo ui code and html code below.Also thought to use Session to store values of selected checkbox but i don't know is it right way or not.
Please guide me as soon as possible.
<div class="dashboardCharts" id="grid-display">
<div class="count-detail-top right">
<div class="count-detail-bg right">
<ul id="ulOptions">
<li id="Employee" data-type="employee">Employee</li>
<li id="Visitor" data-type="visitor">Visitor</li>
</ul>
</div>
</div>
#(Html.Kendo().Grid<xyz.Models.abcModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Employee_id).Title("Alert On").Width(200)
.ClientTemplate("<input type=\"checkbox\" class=\"checkbox\" data-id=\"#= Employee_id#\"/>").Sortable(false);
columns.Bound(c => c.Employee_name).Title("Employee Name");
})
.NoRecords("No Records Found")
.Events(e => e.DataBound("onDataBound"))
.DataSource(dataSource => dataSource
.Transport(transport =>
transport
.Read(read => read.Url(DataUrl))
.ParameterMap("parameterMap")
))
)
</div>
//code in script :
<script>
function onDataBound(e) {
$(".checkbox").bind("click", function (e) {
e.stopPropagation();
$(e.target).closest("tr").toggleClass("k-state-selected");
var tr = $(e.target).closest("tr");
var chk = $(tr).find(".checkbox");
var selected = $(chk).attr("data-id");
var a = selectedIDs.includes(selected);
if (a != true) {
if ($(chk).prop("checked")) {
selectedIDs.push(selected);
}
else {
selectedIDs.pop(selected);
}
}
});
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
for (var i = 0; i < gridDataView.length; i++) {
var panelApplicationId = gridDataView[i].Checkbox;
if (ShouldBeChecked(panelApplicationId)) {
$('#grid tr td input').eq(i).prop("checked", true);
}
}
}
$(document).on('click', 'input.checkbox', function (e) {
var checked = $(this).prop("checked");
var gridDataView = $("#grid").data().kendoGrid.dataSource.view();
console.log(gridDataView);
var idx = $(this).closest("tr").find("td:nth-child(1)").text();
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].ID == idx) {
gridData[i].Checkbox = checked;
break;
}
}
});
function ShouldBeChecked(panelApplicationId) {
var shouldBeChecked = false;
var gridData = $("#grid").data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].Checkbox == panelApplicationId) {
if (gridData[i].Checkbox) {
shouldBeChecked = true;
}
break;
}
}
return shouldBeChecked;
}
</script>
code for selected checkbox and and not selected checkbox.
<input type="checkbox" class="checkbox" data-id="34" checked="checked">
<input type="checkbox" class="checkbox" data-id="30">
As mentioned by OP in question-comment as of the 2017 R2 release, there is a grid-option persistselection
Kendo-versions before that, can add their own code, storing the selection in the change-event, and restoring it in the databoundevent as shown by Kendo in persist-row-selection:
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
(See also this SO-question.)

Categories

Resources