Is it possible to change the editoptions value of jqGrid's edittype:"select"? - select

I am using jqGrid 3.8.1. I want to change the pull-down values of a combobox based on the selected value of another combobox. That's why I am searching on how to change the editoptions:value of an edittype:"select".
Here's the sample jqGrid code:
<%# page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<script type="text/javascript" src="<c:url value="/js/jquery/grid.locale-ja.js" />" charset="UTF-8"></script>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/jquery/ui.jqgrid.css" />"/>
<script src="<c:url value="/js/jquery/jquery.jqGrid.min.js" />" type="text/javascript"></script>
<table id="rowed5"></table>
<script type="text/javascript" charset="utf-8">
var lastsel2;
$("#rowed5").jqGrid({
datatype: "local",
height: 250,
colNames:['ID Number','Name', 'Stock', 'Ship via','Notes'],
colModel:[
{name:'id',index:'id', width:90, sorttype:"int", editable: true},
{name:'name',index:'name', width:150,editable: true,editoptions:{size:"20",maxlength:"30"}},
{name:'stock',index:'stock', width:60, editable: true,edittype:"checkbox",editoptions: {value:"Yes:No"}},
{name:'ship',index:'ship', width:90, editable: true,edittype:"select",editoptions:{value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX;AR1:ARAMEX123456789"}},
{name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}
],
caption: "Input Types",
resizeStop: function (newwidth, index) {
var selectedRowId = $("#rowed5").getGridParam('selrow');
if(selectedRowId) {
//resize combobox proportionate to column size
var selectElement = $('[id="' + selectedRowId + '_ship"][role="select"]');
if(selectElement.length > 0){
$(selectElement).width(newwidth);
}
}
}
,
onSelectRow: function(id){
if(id && id!==lastsel2){
//$(this).saveRow(lastsel2, true);
$(this).restoreRow(lastsel2);
$(this).editRow(id,true);
lastsel2=id;
$(this).scroll();
//resize combobox proportionate to column size
var rowSelectElements = $('[id^="' + id + '_"][role="select"]');
if(rowSelectElements.length > 0) {
$(rowSelectElements).each(function(index, element){
var name = $(element).attr('name');
var columnElement = $('#rowed5_' + name);
if(columnElement.length > 0) {
var columnWidth = $(columnElement).width();
$(element).width(columnWidth);
}
});
}
}
}
});
var mydata2 = [
{id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx"},
{id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime"},
{id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT"},
{id:"45678",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX123456789"},
{id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx"},
{id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FedEx"},
{id:"76543",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX"},
{id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TNT"},
{id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx"}
];
for(var i=0;i < mydata2.length;i++) {
$("#rowed5").jqGrid('addRowData',mydata2[i].id,mydata2[i]);
}
</script>
Scenario:
All ship will be displayed as initial load.
If the stock column changes to Yes, ship will display only FedEx, TNT.
If the stock column changes to No, ship will display only InTime, ARAMEX, ARAMEX123456789.
How can I change the options?

I solved it by trial and error. Want to share it, please refer to the below snippet. The changes are on onSelectRow function.
onSelectRow: function(id){
if(id && id!==lastsel2){
//$(this).saveRow(lastsel2, true);
$(this).restoreRow(lastsel2);
// get the selected stock column value before the editRow
var stockValue = $("#rowed5").jqGrid('getCell', id, 'stock');
if( stockValue == 'Yes') {
$("#rowed5").jqGrid('setColProp', 'ship', { editoptions: { value: 'FE:FedEx;TN:TNT'} });
} else if( stockValue == 'No') {
$("#rowed5").jqGrid('setColProp', 'ship', { editoptions: { value: 'IN:InTime;AR:ARAMEX;AR1:ARAMEX123456789'} });
}
$(this).editRow(id,true);
lastsel2=id;
$(this).scroll();
//resize combobox proportionate to column size
var rowSelectElements = $('[id^="' + id + '_"][role="select"]');
if(rowSelectElements.length > 0) {
$(rowSelectElements).each(function(index, element){
var name = $(element).attr('name');
var columnElement = $('#rowed5_' + name);
if(columnElement.length > 0) {
var columnWidth = $(columnElement).width();
$(element).width(columnWidth);
}
});
}
}
}

Related

Chartjs stacked bar separate tooltip for all stacked

I want to make a separate tooltip for every stacked bar, Ex. My demo "2022-01-17" has TWO stacked bars with FOUR values but I need a total of Stack 1 group and Stack 2 group
I've reviewed most of the options in chartjs https://www.chartjs.org/docs/3.5.1/samples/bar/stacked-groups.html
var barChartData = {
labels: ["2022-01-17","2022-01-18","2022-01-19","2022-01-20","2022-01-21","2022-01-22","2022-01-23","2022-01-24","2022-01-25","2022-01-26","2022-01-27","2022-01-28","2022-01-29","2022-01-30"],
datasets: [{"label":"Product 2","data":["292.53","328.5","273.83","305.44","260.33","251.87","118.15","253.95","86.64","87.78","116.68","295.49","61.32","83.78"],"backgroundColor":"#66bb6a","borderColor":"#66bb6a","pointBackgroundColor":"#66bb6a","stack":"Stack 0"},{"label":"Product ","data":["1522.27","1844.83","1581.01","2767.68","2821.36","2940.31","2876.1","2037.79","1593.01","1900.86","1607.21","2188.92","2428.74","2508.81"],"backgroundColor":"#1b5e20","borderColor":"#1b5e20","pointBackgroundColor":"#1b5e20","stack":"Stack 0"},{"label":"Product 2","data":["200","4.14","28.51","13.68","0","0","19.93","0","0","0","10.47","23.05","9.42","10.58"],"backgroundColor":"#ffcdd2","borderColor":"#ffcdd2","pointBackgroundColor":"#ffcdd2","stack":"Stack 1"},{"label":"Product ","data":["680.2","536.51","524.41","479.69","453.19","521.87","530.57","485.13","440.25","591.29","722.73","711.58","686.63","510.72"],"backgroundColor":"#ef9a9a","borderColor":"#ef9a9a","pointBackgroundColor":"#ef9a9a","stack":"Stack 1"}]
};
const footer = (tooltipItems) => {
let sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += tooltipItem.parsed.y;
});
return 'Sum: ' + sum;
};
var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
interaction: {
intersect: false,
mode: 'index',
},
plugins: {
tooltip: {
callbacks: {
footer: (tooltipItem) => {
let sum = 0;
tooltipItem.forEach(function(tooltipItem) {
sum += tooltipItem.parsed.y;
});
return 'Sum: ' + sum;
}
}
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.0/dist/chart.min.js"></script>
<canvas id="canvas" height="100"></canvas>
to get the total of each stack, you can use the dataPoints found in the tooltip context
and use the dataset labels to group by each stack
// group stacks
const groups = {};
tooltip.dataPoints.forEach(function (point) {
if (groups.hasOwnProperty(barChartData.datasets[point.datasetIndex].label)) {
groups[barChartData.datasets[point.datasetIndex].label] += parseFloat(barChartData.datasets[point.datasetIndex].data[point.dataIndex]);
} else {
groups[barChartData.datasets[point.datasetIndex].label] = parseFloat(barChartData.datasets[point.datasetIndex].data[point.dataIndex]);
}
});
e.g. --> {"Product 2":492.53,"Product ":2202.4700000000003}
then use the external option to create a custom tooltip
see following working snippet...
$(document).ready(function() {
var barChartData = {
labels: ["2022-01-17","2022-01-18","2022-01-19","2022-01-20","2022-01-21","2022-01-22","2022-01-23","2022-01-24","2022-01-25","2022-01-26","2022-01-27","2022-01-28","2022-01-29","2022-01-30"],
datasets: [{"label":"Product 2","data":["292.53","328.5","273.83","305.44","260.33","251.87","118.15","253.95","86.64","87.78","116.68","295.49","61.32","83.78"],"backgroundColor":"#66bb6a","borderColor":"#66bb6a","pointBackgroundColor":"#66bb6a","stack":"Stack 0"},{"label":"Product ","data":["1522.27","1844.83","1581.01","2767.68","2821.36","2940.31","2876.1","2037.79","1593.01","1900.86","1607.21","2188.92","2428.74","2508.81"],"backgroundColor":"#1b5e20","borderColor":"#1b5e20","pointBackgroundColor":"#1b5e20","stack":"Stack 0"},{"label":"Product 2","data":["200","4.14","28.51","13.68","0","0","19.93","0","0","0","10.47","23.05","9.42","10.58"],"backgroundColor":"#ffcdd2","borderColor":"#ffcdd2","pointBackgroundColor":"#ffcdd2","stack":"Stack 1"},{"label":"Product ","data":["680.2","536.51","524.41","479.69","453.19","521.87","530.57","485.13","440.25","591.29","722.73","711.58","686.63","510.72"],"backgroundColor":"#ef9a9a","borderColor":"#ef9a9a","pointBackgroundColor":"#ef9a9a","stack":"Stack 1"}]
};
var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
interaction: {
intersect: false,
mode: 'index',
},
plugins: {
tooltip: {
enabled: false,
position: 'nearest',
external: function (context) {
// init
const {chart, tooltip} = context;
// remove old tooltip
var container = chart.canvas.parentNode.querySelector('.tooltip');
if (container) {
chart.canvas.parentNode.removeChild(container);
}
// determine if tooltip exists
if (tooltip.opacity === 0) {
return;
}
// group stacks
const groups = {};
tooltip.dataPoints.forEach(function (point) {
if (groups.hasOwnProperty(barChartData.datasets[point.datasetIndex].label)) {
groups[barChartData.datasets[point.datasetIndex].label] += parseFloat(barChartData.datasets[point.datasetIndex].data[point.dataIndex]);
} else {
groups[barChartData.datasets[point.datasetIndex].label] = parseFloat(barChartData.datasets[point.datasetIndex].data[point.dataIndex]);
}
});
// build tooltip rows
var rows = '';
Object.keys(groups).forEach(function (groupName) {
rows += renderTemplate('template-tooltip-row', {
group: groupName,
value: groups[groupName].toLocaleString(undefined, {minimumFractionDigits: 2})
});
});
// build tooltip
chart.canvas.parentNode.insertAdjacentHTML('beforeEnd', renderTemplate('template-tooltip', {
rows: rows,
title: tooltip.title[0]
}));
// position tooltip
const {offsetLeft: positionX, offsetTop: positionY} = chart.canvas;
container = chart.canvas.parentNode.querySelector('.tooltip');
container.style.left = positionX + tooltip.caretX + 'px';
container.style.top = positionY + tooltip.caretY + 'px';
container.style.font = tooltip.options.bodyFont.string;
container.style.padding = tooltip.options.padding + 'px ' + tooltip.options.padding + 'px';
}
}
}
}
});
/**
* render html template
* #param {string} templateId - id of html template
* #param {object} templateValues - values for each template placeholder
* #return {string} template content
*/
function renderTemplate(templateId, templateValues) {
var propHandle; // property key
var templateText; // html template content
var templateValue; // value for template placeholder
// get template content, replace each placeholder with value
templateText = document.querySelector('#' + templateId).innerHTML;
if (templateValues) {
for (propHandle in templateValues) {
if (templateValues.hasOwnProperty(propHandle)) {
templateValue = '';
// convert template value to string
if (templateValues[propHandle] !== null) {
if (templateValues[propHandle].hasOwnProperty('results')) {
templateValue = encodeURIComponent(JSON.stringify(templateValues[propHandle].results));
} else {
templateValue = templateValues[propHandle].toString();
}
}
// handle dollar sign in template value
if (templateValue.indexOf('$') > -1) {
templateValue = templateValue.replace(new RegExp('\\$', 'g'), '$$$');
}
// replace template placeholder(s) with template value
if (templateText.indexOf('{{' + propHandle + '}}') > -1) {
templateText = templateText.replace(
new RegExp('{{' + propHandle + '}}', 'g'),
templateValue
);
}
}
}
}
return templateText.trim();
}
});
.align-right {
text-align: right;
}
.table {
border-collapse: separate;
border-spacing: 0vw 0vw;
display: table;
}
.table-body {
display: table-row-group;
}
.table-cell {
display: table-cell;
padding: 4px;
}
.table-foot {
display: table-footer-group;
}
.table-head {
display: table-header-group;
}
.table-row {
display: table-row;
}
.title {
font-weight: bold;
}
.tooltip {
background-color: rgba(0, 0, 0, 0.85);
border-radius: 3px;
color: #ffffff;
pointer-events: none;
position: absolute;
transform: translate(-50%, 0);
transition: all 0.1s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.0/dist/chart.min.js"></script>
<canvas id="canvas" height="100"></canvas>
<script id="template-tooltip" type="text/html">
<div class="tooltip">
<div class="title">{{title}}</div>
<div class="table">
<div class="table-body">{{rows}}</div>
</div>
</div>
</script>
<script id="template-tooltip-row" type="text/html">
<div class="table-row">
<div class="table-cell title">{{group}}:</div>
<div class="table-cell align-right">{{value}}</div>
</div>
</script>

adding multiple (dynamic number) google charts in page

Am trying to create a test report from the xml file generated from the test suite run. I have to generate the google line chart for each activity in an application node in xml. Its dynamic and we dont know how many activities will be there under application tag.
so far i tried to generate the line charts using the callback method in a for loop but, all the graphs are having the same data. when i debugged the code i found that the code in call back method to create the datatable is always executing for the last activity and generating the same chart for each activity.
here is the code i tried
html
<div id="container">
<div id="report" class="table-responsive">
<select id="app" name="app" aria-placeholder="Select Application">
<option>-- Select Application --</option>
</select>
<select id="activity" name="activity" aria-placeholder="Select Activity">
<option>-- Select Activity --</option>
</select>
<select id="type" name="type" aria-placeholder="Select StartupType">
<option value="coldstart" >Cold</option>
<option value="warmstart" selected>Warm</option>
</select>
<br/>
<div id="chartContainer">
</div>
</div>
<div align="center" class="loader">
<img src="images/loader.gif" id="load" width="400" height="400" align="absmiddle" />
</div>
</div>
javascript
var appXml;
var summaryXml;
$(document).ready(function () {
prepareCharts();
$("#app").change(function () {
var app = $(this).val();
if (app != "") {
$(appXml).find('package').each(function () {
if ($(this).attr('appname') == app) {
var options = '<option value="">-- Select activity --</option>';
$(this).find('activity').each(function () {
options += '<option value="' + $(this).attr('activityname') + '">' + $(this).attr('activityname') + '</option>';
});
$('#activity').html(options);
}
});
}
});
$("#activity").change(function () {
if ($(this).val() != "")
drawActivityChart();
else
drawActivityCharts(appXml, $('#type').val());
});
$('#type').change(function () {
var type = $(this).val();
if ($('#activity').val() == "")
drawActivityCharts(appXml, type);
else
drawActivityChart();
});
});
function prepareCharts() {
$.ajax({
type: "GET",
url: "Startuptime.xml",
dataType: "xml",
success: drawCharts
});
}
function drawCharts(xml) {
console.log('drawing charts');
appXml = xml;
prepareDropdowns(xml);
drawActivityCharts(xml);
}
function prepareDropdowns(xml) {
var options = '<option value="">-- Select application --</option>';
$(xml).find('package').each(function () {
options += '<option value="' + $(this).attr('appname') + '">' + $(this).attr('appname') + '</option>';
});
$('#app').html(options);
$('#app option:nth-child(2)').attr('selected', 'selected').change();
}
function drawActivityCharts(xml, type) {
$('#chartContainer').children().remove();
if (typeof type === 'undefined')
type = 'warmstart';
google.charts.load('current', { 'packages': ['corechart'] });
var app = $('#app').val();
$(xml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
var i = 1;
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
console.log(i);
console.log(activityName);
i++;
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
google.charts.setOnLoadCallback(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).children(type).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
});
}
});
}
});
}
function drawActivityChart() {
$('#chartContainer').children().remove();
google.charts.load('current', { 'packages': ['corechart'] });
var app = $('#app').val();
var activity = $('#activity').val();
var type = $('#type').val();
$(appXml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
if (activityName == activity) {
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
google.charts.setOnLoadCallback(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
});
}
}
});
}
});
}
drawActivityCharts() is the method which has to draw the activity charts
and xml schema will be like below.
<?xml version='1.0' encoding='UTF-8' ?>
<appstartuptime>
<package appname="appname" name="packagename" packageversion="version">
<activity activityname="activityname">
<coldstart numberoftimes="1">
<displaytime>
<timetoinitialdisplay>841</timetoinitialdisplay>
</displaytime>
</coldstart>
</activity>
<activity activityname="activityname">
<warmstart numberoftimes="2">
<displaytime>
<timetoinitialdisplay>454</timetoinitialdisplay>
</displaytime>
<displaytime>
<timetoinitialdisplay>467</timetoinitialdisplay>
</displaytime>
</warmstart>
</activity>
</package>
</appstartuptime>
both google.charts.load and google.charts.setOnLoadCallback only need to be called once per page load.
in addition, google.charts.load will wait on the page to load by default,
as such, it can be used in place of $(document).ready
you can also include google's callback in the load statement.
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
or use the promise it returns.
google.charts.load('current', {
packages:['corechart']
}).then(drawChart);
given this, recommend loading google first,
then you can draw as many charts as needed.
i didn't go thru all of the code, but something similar to the following should work...
var appXml;
var summaryXml;
google.charts.load('current', {
packages:['corechart']
}).then(function () {
prepareCharts();
$("#app").change(function () {
var app = $(this).val();
if (app != "") {
$(appXml).find('package').each(function () {
if ($(this).attr('appname') == app) {
var options = '<option value="">-- Select activity --</option>';
$(this).find('activity').each(function () {
options += '<option value="' + $(this).attr('activityname') + '">' + $(this).attr('activityname') + '</option>';
});
$('#activity').html(options);
}
});
}
});
$("#activity").change(function () {
if ($(this).val() != "")
drawActivityChart();
else
drawActivityCharts(appXml, $('#type').val());
});
$('#type').change(function () {
var type = $(this).val();
if ($('#activity').val() == "")
drawActivityCharts(appXml, type);
else
drawActivityChart();
});
});
function prepareCharts() {
$.ajax({
type: "GET",
url: "Startuptime.xml",
dataType: "xml",
success: drawCharts
});
}
function drawCharts(xml) {
console.log('drawing charts');
appXml = xml;
prepareDropdowns(xml);
drawActivityCharts(xml);
}
function prepareDropdowns(xml) {
var options = '<option value="">-- Select application --</option>';
$(xml).find('package').each(function () {
options += '<option value="' + $(this).attr('appname') + '">' + $(this).attr('appname') + '</option>';
});
$('#app').html(options);
$('#app option:nth-child(2)').attr('selected', 'selected').change();
}
function drawActivityCharts(xml, type) {
$('#chartContainer').children().remove();
if (typeof type === 'undefined')
type = 'warmstart';
var app = $('#app').val();
$(xml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
var i = 1;
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
console.log(i);
console.log(activityName);
i++;
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).children(type).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
}
});
}
});
}
function drawActivityChart() {
$('#chartContainer').children().remove();
var app = $('#app').val();
var activity = $('#activity').val();
var type = $('#type').val();
$(appXml).find('package').each(function () {
var that = this;
if ($(that).attr('appname') == app) {
$(that).find('activity').each(function () {
var activityName = $(this).attr('activityname');
if (activityName == activity) {
if ($(this).find(type).length > 0) {
that = this;
$('#chartContainer').append('<div id="' + activityName + '"></div>')
var data = new google.visualization.DataTable();
data.addColumn('number', 'Occurance');
data.addColumn('number', 'Time');
var row = 1;
$(that).find('displaytime').each(function () {
data.addRow([row, parseFloat($.trim($(this).find('timetoinitialdisplay').text()))]);
console.log(row + " " + parseFloat($.trim($(this).find('timetoinitialdisplay').text())));
row++;
});
// Set chart options
var options = {
'title': activityName,
'width': 800,
'height': 200
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById(activityName));
chart.draw(data, options);
}
}
});
}
});
}

SharePoint bulk update of multiple list items

I am currently working with binding SharePoint list items using JQuery datatables and rest API with the following code from Microsoft samples. I want to extend the sample to include multiple selection of row items with check boxes so that I can then another method to update the selected items. Please let me if this is possible with any guidance
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<table id="requests" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Business unit</th>
<th>Category</th>
<th>Status</th>
<th>Due date</th>
<th>Assigned to</th>
</tr>
</thead>
</table>
<script>
// UMD
(function(factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], function ($) {
return factory( $, window, document );
});
}
else if (typeof exports === 'object') {
// CommonJS
module.exports = function (root, $) {
if (!root) {
root = window;
}
if (!$) {
$ = typeof window !== 'undefined' ?
require('jquery') :
require('jquery')( root );
}
return factory($, root, root.document);
};
}
else {
// Browser
factory(jQuery, window, document);
}
}
(function($, window, document) {
$.fn.dataTable.render.moment = function (from, to, locale) {
// Argument shifting
if (arguments.length === 1) {
locale = 'en';
to = from;
from = 'YYYY-MM-DD';
}
else if (arguments.length === 2) {
locale = 'en';
}
return function (d, type, row) {
var m = window.moment(d, from, locale, true);
// Order and type get a number value from Moment, everything else
// sees the rendered value
return m.format(type === 'sort' || type === 'type' ? 'x' : to);
};
};
}));
</script>
<script>
$(document).ready(function() {
$('#requests').DataTable({
'ajax': {
'url': "../_api/web/lists/getbytitle('IT Requests')/items?$select=ID,BusinessUnit,Category,Status,DueDate,AssignedTo/Title&$expand=AssignedTo/Title",
'headers': { 'Accept': 'application/json;odata=nometadata' },
'dataSrc': function(data) {
return data.value.map(function(item) {
return [
item.ID,
item.BusinessUnit,
item.Category,
item.Status,
new Date(item.DueDate),
item.AssignedTo.Title
];
});
}
},
columnDefs: [{
targets: 4,
render: $.fn.dataTable.render.moment('YYYY/MM/DD')
}]
});
});
</script>

Ionic Local storage put information into array

Here is the code
Controller.js
$scope.addFavorite = function (index) {
$scope.temp = {
id: index
};
$scope.dish = $localStorage.getObject('favorites', '{}');
console.log($localStorage.get('favorites'));
$localStorage.storeObject('favorites', JSON.stringify($scope.temp));
var favorites = $localStorage.getObject('favorites');
console.log(favorites);
favoriteFactory.addToFavorites(index);
$ionicListDelegate.closeOptionButtons();
}
Service.js
.factory('favoriteFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
var favFac = {};
var favorites = [];
favFac.addToFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
};
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
}
}
}
favFac.getFavorites = function () {
return favorites;
};
return favFac;
}])
.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}])
I want to make a Favorites function, and I want to put every item's ID that marked into an array.
But, it couldn't expand the array and only change the value.
Did I make something wrong on here? Or maybe I put a wrong method on here?
Thank you in advance!
I just create logic for storing object, you have to made logic for remove object from localstorage.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="item in items">
{{item.item_name}}
<button ng-click="addFavorite(item.id)">Add to Favorite</button>
<br><hr>
</div>
</body>
</html>
<script type="text/javascript">
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http)
{
$scope.items = [
{id:1,item_name:'Apple'},
{id:2,item_name:'Banana'},
{id:3,item_name:'Grapes'},
]
$scope.addFavorite = function (index)
{
if(localStorage.getItem('favorites')!=undefined)
{
var old_favorite = JSON.parse(localStorage.getItem('favorites'));
var obj = {index:index};
old_favorite.push(obj);
localStorage.setItem('favorites',JSON.stringify(old_favorite));
}
else
{
var obj = [{index:index}];
localStorage.setItem('favorites',JSON.stringify(obj));
}
}
});
</script>

How to Add jQuery UI DatePicker Button TRIGGER SCRIPT

I have a working jQuery UI DatePicker script that only
displays WED & SAT (see MAIN SCRIPT below).
I also have a working jQuery UI DatePicker script that adds
a button image to trigger the DatePicker (see TRIGGER SCRIPT BELOW).
How can I integrate the TRIGGER SCRIPT into the MAIN SCRIPT?
I know this is simple but this newbie can't figure out out the syntax.
Sorry about that....
Trigger script:
<script>
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "css/blitzer/images/calendar.gif",
buttonImageOnly: true
});
});
</script>
Main script:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Disable Certains Days in a Week using jQuery UI DatePicker</title>
<link rel="stylesheet" href="css/redmond/jquery-ui-1.8.6.custom.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 0 || day == 1 || day == 2 || day == 4 || day == 5) {
return [false, "somecssclass"]
} else {
return [true, "someothercssclass"]
}
}
});
});
</script>
</head>
<body>
<input id="datepicker"/>
</body>
</html>
<input type="button" name="date" id="popupDatepicker">
/* create an array of days which need to be disabled */
var disabledDays = ["2-21-2010","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"];
/* utility functions */
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if(ArrayContains(disabledDays,(m+1) + '-' + d + '-' + y) || new Date() > date) {
//console.log('bad: ' + (m+1) + '-' + d + '-' + y + ' / ' + disabledDays[i]);
return [false];
}
}
//console.log('good: ' + (m+1) + '-' + d + '-' + y);
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
/* taken from mootools */
function ArrayIndexOf(array,item,from){
var len = array.length;
for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
if (array[i] === item) return i;
}
return -1;
}
/* taken from mootools */
function ArrayContains(array,item,from){
return ArrayIndexOf(array,item,from) != -1;
}
/* create datepicker */
jQuery(document).ready(function() {
jQuery('#date').datepicker({
minDate: new Date(2010, 0, 1),
maxDate: new Date(2010, 5, 31),
dateFormat: 'DD, MM, d, yy',
constrainInput: true,
beforeShowDay: noWeekendsOrHolidays
});
});
In your main script:
$(document).ready(function(){
$( "#datepicker" ).datepicker(
{ showOn: "button",
buttonImage: "css/blitzer/images/calendar.gif",
buttonImageOnly: true});
});
Solution Found: How to Add jQuery UI DatePicker Button TRIGGER SCRIPT.
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "css/blitzer/images/calendar.gif",
buttonImageOnly: true,
beforeShowDay: function(day) {
var day = day.getDay();
if (day == 0 || day == 1 || day == 3 || day == 4 || day == 6) {
return [false, "somecssclass"]
} else {
return [true, "someothercssclass"]
}
}
});
});
</script>