Dropdown value change style of pages dynamically - javascript

I am building a muti-page website with Kendo UI for Jquery. I have a dropdown to select the style the user want. For now I can change the style, but it doesn't stick; as soon as I refresh the page it goes back to the default style. I want the style to also change for all the other pages.
Here is my code:
HTML
<html>
<head>
<link rel="stylesheet" href="css/kendo.common.min.css">
<link rel="stylesheet" href="css/kendo.default.min.css"/>
<script src="script/jquery.min.js"></script>
<script src="script/kendo.all.min.js"></script>
</head>
<body class="k-content">
<label for="theme">Theme:</label>
<input id="theme" name="theme">
<button class="k-button">Export Immagine</button>
<button class="k-button">Export Excel</button>
</body>
</html>
Jquery
$('#theme').kendoDropDownList({
dataSource: [
{ text: "Original", value: "default" },
{ text: "Black", value: "black" },
{ text: "Blue Opal", value: "blueopal" },
{ text: "Metro", value: "metro" },
{ text: "Silver", value: "silver" }
],
dataTextField: "text",
dataValueField: "value",
change: function (e) {
var theme = (this.value() || "default").toLowerCase();
changeTheme(theme);
}
});
// loads new stylesheet
function changeTheme(skinName, animate) {
var doc = document,
kendoLinks = $("link[href*='kendo.']", doc.getElementsByTagName("head")[0]),
commonLink = kendoLinks.filter("[href*='kendo.common']"),
skinLink = kendoLinks.filter(":not([href*='kendo.common'])"),
href = location.href,
skinRegex = /kendo\.\w+(\.min)?\.css/i,
extension = skinLink.attr("rel") === "stylesheet" ? ".css" : ".less",
url = commonLink.attr("href").replace(skinRegex, "kendo." + skinName + "$1" + extension);
var theme = $('#theme').getKendoDropDownList().value();
$('.k-chart').each(function () {
var chart = $(this).data('kendoChart');
chart.options.theme = skinName;
chart.setOptions({ theme: theme });;
});
function preloadStylesheet(file, callback) {
var element = $("<link rel='stylesheet' media='print' href='" + file + "'").appendTo("head");
setTimeout(function () {
callback();
element.remove();
}, 100);
}
function replaceTheme() {
var oldSkinName = $(doc).data("kendoSkin"),
newLink;
if (kendo.support.browser.msie) {
newLink = doc.createStyleSheet(url);
} else {
newLink = skinLink.eq(0).clone().attr("href", url);
newLink.insertBefore(skinLink[0]);
}
skinLink.remove();
$(doc.documentElement).removeClass("k-" + oldSkinName).addClass("k-" + skinName);
}
if (animate) {
preloadStylesheet(url, replaceTheme);
} else {
replaceTheme();
}
};
I know I have to use sessionStorage, but I don't really know how to implement that with Kendo. Can someone help me?

Set the session storage value inside the changeTheme function with the chosen theme name:
sessionStorage.setItem('user.theme', skinName);
Then check for it on page load, and set it if any value is set:
let userTheme = sessionStorage.getItem('user.theme');
if (userTheme) {
changeTheme(userTheme);
$('#theme').getKendoDropDownList().value(userTheme);
}
Dojo

Related

Adding data in node of jstree through dropdown not working properly

I am trying to add a dropdown in a node and want to be able to create and remove the nodes. I am able to do that but whenever i create/remove a node the dropdown values that i have selected are removed from where the node is created or removed. I am using select2 for dropdown if that helps.
below is the link for demonstration
https://www.arsallodhi.com/jstree/index.html
thanks in advance
I think redraw method is called which does removes the values. So i tried to catch it but couldnt.
<html>
<head>
<style>
.jstree-default .jstree-node, .jstree-leaf {
min-height: 35px !important;
}
.jstree-open .jstree-node {
padding-top: 15px !important;
}
</style>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css"/>
</head>
<body>
<div id="jstreee">
<ul>
<li class="jstree-open">
Organization
</li>
</ul>
</div>
<script src="https://kendo.cdn.telerik.com/2019.2.514/js/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<script>
function formatDropdown1(option) {
if (option.id) {
return option.text;
} else {
return '';
}
};
function addTagValueClass() {
$('.tag').select2({
placeholder: '',
allowClear: true,
tags: true,
templateSelection: formatDropdown1,
});
}
var counter = 0;
function customMenu2(node) {
var position = 'inside';
var parent;
var selected_id;
selected_id = parent = $('#jstreee').jstree('get_selected');
counter++;
var node_data;
node_data = "<li class='node-li'><select data-live-search='true' class='tag' placeholder='Tag'><option></option><option value='volvo'>Project</option><option value='saab'>Owner</option><option value='mercede'>Department</option><option value='audi'>Business Unit</option></select></li>"
var items = {
createItem: {
label: "Add Node",
action: function () {
$('#jstreee').jstree().create_node(parent, {"id": "ajson5" + counter, "text": node_data}, position
, function () {
addTagValueClass();
$('#jstreee').jstree().open_node('#' + parent);
});
}
},
deleteItem: {
label: "Remove Node",
action: function () {
if (selected_id != "j1_1") {
$('#jstreee').jstree().delete_node(selected_id);
addTagValueClass();
}
}
}
};
return items;
}
$('#jstreee').on('open_node.jstree', function (e, data) {
addTagValueClass();
});
$('#jstreee').jstree({
"core": {"check_callback": true, "themes": {"icons": false}, "toggle_node": true}, // so that modifying operations work
"plugins": ["contextmenu"], contextmenu: {items: customMenu2}
});
</script>
</body>
</html>
I want that the values which i have set through the dropdown remain even when a node is created or removed.

Highlight selected jsGrid row

I found this example which highlights a row after it has been selected but the problem with it is that it keeps the previous row(s) highlighted after another one has been selected.
Here's part of the code
//js
rowClick: function(args) {
var $row = this.rowByItem(args.item);
$row.toggleClass("highlight");
},
//css
tr.highlight td.jsgrid-cell {
background-color: green;
}
I can't find a solution to unhighlight the previously selected row
A little late to the party on this one, however the accepted answer by #Narenda didn't completely solve my problem. This may help someone else that stumbles across this later.
If you need a single select only, here's a way of doing it:
Extend the jsGrid plugin with a method to find a row by index:
jsGrid.Grid.prototype.rowByIndex = function(arg){
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
Modify the rowClick function in #Narenda's answer:
rowClick: function ( args ) {
//Deselect all rows
for(var i = 0; i<this.data.length; i++){
this.rowByIndex(i).removeClass("jsgrid-highlight-row");
}
//Everything else as per the previous answer
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.jsgrid-highlight-row');
if (selectedRow.length) {
selectedRow.toggleClass('jsgrid-highlight-row');
};
$row.toggleClass("jsgrid-highlight-row");
//Any other code to run on item click
}
And add some CSS. This mimics the row hover in the default theme:
tr.jsgrid-highlight-row td.jsgrid-cell {
background:#c4e2ff;
border-color:#c4e2ff;
}
You can achieve by this following steps
First on row click you need to get selected row like this
var selectedRow = $("#jsGrid").find('table tr.highlight').
Then you can use
selectedRow.toggleClass('highlight') or selectedRow.removeClass('highlight')
DEMO
$("#jsGrid").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method Need to set auto load true
autoload: true,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
var data = [{
nickname: "Test",
email: "t#gmail.com"
}, {
nickname: "Test 1",
email: "t1#gmail.com"
}, {
nickname: "Test 2",
email: "t2#gmail.com"
}, {
nickname: "Test 3",
email: "t3#gmail.com"
}];
return data;
}
},
rowClick: function(args) {
var $row = this.rowByItem(args.item),
selectedRow = $("#jsGrid").find('table tr.highlight');
if (selectedRow.length) {
selectedRow.toggleClass('highlight');
};
$row.toggleClass("highlight");
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}]
});
tr.highlight td.jsgrid-cell {
background-color: green;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>
If you came looking for a solution in which only 1 line is selected and which also deselects the same line, here is the solution:
selectedVal = null;
$(document).ready(function(){
jsGrid.Grid.prototype.rowByIndex = function(arg) {
//this._content.find("tr")[arg] returns a DOM element instead of a jQuery object
//Pass the DOM element to the find method to get a jQuery object representing it
return this._content.find(this._content.find("tr")[arg]);
};
});
rowClick: function (args) {
selectedVal = args.item;
let $row = this.rowByItem(args.item);
if ($row.hasClass("highlight") === false) {
//Deseleciona todas as linhas
for (let i = 0; i < this.data.length; i++) {
this.rowByIndex(i).removeClass("highlight");
}
$row.toggleClass("highlight");
} else {
selectedVal = null;
$row.toggleClass("highlight");
}
console.log(selectedVal);
}

How to scan a barcode with livestream through webbrowser on on mobile phone in javascript?

I'm trying to make a way to scan irl barcodes that I have printed out on paper to scan into my php website. It's only when I use the website on my phone, than I can open my phone camera and scan a barcod while he scans the barcode and sends it to my code. The code can than check my database etc.
I found a beautiful plugin to do this called QuaggaJS, I have been playing around with it and at the moment I come further than taking a picture and let it read the barcode and the sends it to my code but I want to let it scan while I hold my camera in front of the barcode so it will close the camera out of himself. Here is an example(on a desktop it would ask permission to open webcam).
In the end I want a button where I click on in my website that opens my camera so I can scan the code and when he finds a barcode he close the camera and show me the information from the product that has this barcode. Is there someone that can help me with it?
Here is some code that I used and played with. (Only works with taking picture)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script type="text/javascript" src="includes/js/quagga.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<script type="text/javascript" src="includes/js/quagga.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<style>
#interactive.viewport {position: relative; width: 100%; height: auto; overflow: hidden; text-align: center;}
#interactive.viewport > canvas, #interactive.viewport > video {max-width: 100%;width: 100%;}
canvas.drawing, canvas.drawingBuffer {position: absolute; left: 0; top: 0;}
</style>
<script type="text/javascript">
$(function() {
// Create the QuaggaJS config object for the live stream
var liveStreamConfig = {
inputStream: {
type : "LiveStream",
constraints: {
width: {min: 640},
height: {min: 480},
aspectRatio: {min: 1, max: 100},
facingMode: "environment" // or "user" for the front camera
}
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: (navigator.hardwareConcurrency ? navigator.hardwareConcurrency : 4),
decoder: {
"readers":[
{"format":"code_128_reader","config":{}}
]
},
locate: true
};
// The fallback to the file API requires a different inputStream option.
// The rest is the same
var fileConfig = $.extend(
{},
liveStreamConfig,
{
inputStream: {
size: 800
}
}
);
// Start the live stream scanner when the modal opens
$('#livestream_scanner').on('shown.bs.modal', function (e) {
Quagga.init(
liveStreamConfig,
function(err) {
if (err) {
$('#livestream_scanner .modal-body .error').html('<div class="alert alert-danger"><strong><i class="fa fa-exclamation-triangle"></i> '+err.name+'</strong>: '+err.message+'</div>');
Quagga.stop();
return;
}
Quagga.start();
}
);
});
// Make sure, QuaggaJS draws frames an lines around possible
// barcodes on the live stream
Quagga.onProcessed(function(result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 2});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "#00F", lineWidth: 2});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: 'red', lineWidth: 3});
}
}
});
// Once a barcode had been read successfully, stop quagga and
// close the modal after a second to let the user notice where
// the barcode had actually been found.
Quagga.onDetected(function(result) {
if (result.codeResult.code){
$('#scanner_input').val(result.codeResult.code);
Quagga.stop();
setTimeout(function(){ $('#livestream_scanner').modal('hide'); }, 1000);
}
});
// Stop quagga in any case, when the modal is closed
$('#livestream_scanner').on('hide.bs.modal', function(){
if (Quagga){
Quagga.stop();
}
});
// Call Quagga.decodeSingle() for every file selected in the
// file input
$("#livestream_scanner input:file").on("change", function(e) {
if (e.target.files && e.target.files.length) {
Quagga.decodeSingle($.extend({}, fileConfig, {src: URL.createObjectURL(e.target.files[0])}), function(result) {alert(result.codeResult.code);});
}
});
});
</script>
</head>
<body>
<input id="scanner_input" class="form-control" style="width:20%;" placeholder="Barcode" type="text" />
<button class="btn btn-default" type="button" data-toggle="modal" data-target="#livestream_scanner"><i class="fas fa-barcode"></i> Scan</button>
<div class="modal" id="livestream_scanner">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Barcode Scanner</h4>
</div>
<div class="modal-footer">
<label class="btn btn-default pull-left">
<i class="fa fa-camera"></i> Use camera app
<input type="file" accept="image/*;capture=camera" capture="camera" class="hidden" />
</label>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
Best regards
Took me some time to get it done on myself but I found it out. I also had to get a certificate so my website is secure and allows me to use GetUserMedia(); This is my code that I used now. With $code = $_GET['barcode']; I can take the variable to do other stuff with it, all up to yourself.
php code
<button id="opener">Barcode scanner</button>
<div id="modal" title="Barcode scanner">
<span class="found"></span>
<div id="interactive" class="viewport"></div>
</div>
Javascript/QuaggaJS
$(function() {
var App = {
init : function() {
Quagga.init(this.state, function(err) {
if (err) {
console.log(err);
return;
}
App.attachListeners();
App.checkCapabilities();
Quagga.start();
});
},
checkCapabilities: function() {
var track = Quagga.CameraAccess.getActiveTrack();
var capabilities = {};
if (typeof track.getCapabilities === 'function') {
capabilities = track.getCapabilities();
}
this.applySettingsVisibility('zoom', capabilities.zoom);
this.applySettingsVisibility('torch', capabilities.torch);
},
updateOptionsForMediaRange: function(node, range) {
console.log('updateOptionsForMediaRange', node, range);
var NUM_STEPS = 6;
var stepSize = (range.max - range.min) / NUM_STEPS;
var option;
var value;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
for (var i = 0; i <= NUM_STEPS; i++) {
value = range.min + (stepSize * i);
option = document.createElement('option');
option.value = value;
option.innerHTML = value;
node.appendChild(option);
}
},
applySettingsVisibility: function(setting, capability) {
if (typeof capability === 'boolean') {
var node = document.querySelector('input[name="settings_' + setting + '"]');
if (node) {
node.parentNode.style.display = capability ? 'block' : 'none';
}
return;
}
if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
var node = document.querySelector('select[name="settings_' + setting + '"]');
if (node) {
this.updateOptionsForMediaRange(node, capability);
node.parentNode.style.display = 'block';
}
return;
}
},
initCameraSelection: function(){
var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();
return Quagga.CameraAccess.enumerateVideoDevices()
.then(function(devices) {
function pruneText(text) {
return text.length > 30 ? text.substr(0, 30) : text;
}
var $deviceSelection = document.getElementById("deviceSelection");
while ($deviceSelection.firstChild) {
$deviceSelection.removeChild($deviceSelection.firstChild);
}
devices.forEach(function(device) {
var $option = document.createElement("option");
$option.value = device.deviceId || device.id;
$option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
$option.selected = streamLabel === device.label;
$deviceSelection.appendChild($option);
});
});
},
attachListeners: function() {
var self = this;
self.initCameraSelection();
$(".controls").on("click", "button.stop", function(e) {
e.preventDefault();
Quagga.stop();
});
$(".controls .reader-config-group").on("change", "input, select", function(e) {
e.preventDefault();
var $target = $(e.target),
value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
name = $target.attr("name"),
state = self._convertNameToState(name);
console.log("Value of "+ state + " changed to " + value);
self.setState(state, value);
});
},
_accessByPath: function(obj, path, val) {
var parts = path.split('.'),
depth = parts.length,
setter = (typeof val !== "undefined") ? true : false;
return parts.reduce(function(o, key, i) {
if (setter && (i + 1) === depth) {
if (typeof o[key] === "object" && typeof val === "object") {
Object.assign(o[key], val);
} else {
o[key] = val;
}
}
return key in o ? o[key] : {};
}, obj);
},
_convertNameToState: function(name) {
return name.replace("_", ".").split("-").reduce(function(result, value) {
return result + value.charAt(0).toUpperCase() + value.substring(1);
});
},
detachListeners: function() {
$(".controls").off("click", "button.stop");
$(".controls .reader-config-group").off("change", "input, select");
},
applySetting: function(setting, value) {
var track = Quagga.CameraAccess.getActiveTrack();
if (track && typeof track.getCapabilities === 'function') {
switch (setting) {
case 'zoom':
return track.applyConstraints({advanced: [{zoom: parseFloat(value)}]});
case 'torch':
return track.applyConstraints({advanced: [{torch: !!value}]});
}
}
},
setState: function(path, value) {
var self = this;
if (typeof self._accessByPath(self.inputMapper, path) === "function") {
value = self._accessByPath(self.inputMapper, path)(value);
}
if (path.startsWith('settings.')) {
var setting = path.substring(9);
return self.applySetting(setting, value);
}
self._accessByPath(self.state, path, value);
console.log(JSON.stringify(self.state));
App.detachListeners();
Quagga.stop();
App.init();
},
inputMapper: {
inputStream: {
constraints: function(value){
if (/^(\d+)x(\d+)$/.test(value)) {
var values = value.split('x');
return {
width: {min: parseInt(values[0])},
height: {min: parseInt(values[1])}
};
}
return {
deviceId: value
};
}
},
numOfWorkers: function(value) {
return parseInt(value);
},
decoder: {
readers: function(value) {
if (value === 'ean_extended') {
return [{
format: "ean_reader",
config: {
supplements: [
'ean_5_reader', 'ean_2_reader'
]
}
}];
}
return [{
format: value + "_reader",
config: {}
}];
}
}
},
state: {
inputStream: {
type : "LiveStream",
constraints: {
width: {min: 640},
height: {min: 480},
aspectRatio: {min: 1, max: 100},
facingMode: "environment" // or user
}
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: 2,
frequency: 10,
decoder: {
readers : [{
format: "code_128_reader",
config: {}
}]
},
locate: true
},
lastResult : null
};
App.init();
Quagga.onDetected(function(result) {
var code = result.codeResult.code;
Quagga.stop();
window.location.href="scannerview.php?barcode=" + code;
});
});

How to fix offsetWidth of undefined error?

I'm using awesomplete autocomplete plugin with thumbnail and I have index.html and I've <input id="myinput"> element but on my laoyut.html if I didn't put <input id="myinput"> then js give me a this erros
jquery.min.js:2 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined
and my question is what should I do to fix it ?
var input = document.getElementById("myinput");
// Show label but insert value into the input:
new Awesomplete(input, {
list: [{
label: "<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUxdD-Q4nIx3uIg9jBCe1oT5a9MHuWY5_pW4FoZSU-nQd1Y_WJPQ'/> Faceboock",
value: "https://www.facebook.com/"
},
{
label: "<img src='https://hydra-media.cursecdn.com/dota2.gamepedia.com/thumb/2/25/Pounce_icon.png/16px-Pounce_icon.png?version=77c984fc4a9c8ca491ead081322fa738'/> Youtube",
value: "https://www.youtube.com/"
},
{
label: "China",
value: "CN"
},
{
label: "United States",
value: "US"
}
]
});
// You can search for a better version
$(document).find('.awesomplete').on('click', function(e) {
if ($('#myinput').val())
window.location = $('#myinput').val();
//console.log($('#myinput').val());
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet"/>
<input id="myinput" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
You can first check if #myinput is available in the html dom, then you can use the value of it.
var input = $("#myinput");
if (input.size() > 0) {
window.location = input.val();
}
I asume that there will be one div with this specific id. In that case, you can use
if (input.size() === 1) {
So in short, you can replace
$(document).find('.awesomplete').on('click', function(e) {
if ($('#myinput').val())
window.location = $('#myinput').val();
//console.log($('#myinput').val());
});
with
$(document).find('.awesomplete').on('click', function(e) {
var input = $('#myinput');
if (input.size() === 1) {
window.location = input.val();
}
});

slickgrid custom dropdown editor

I am working a on slickgrid where one cell needs to show a dropdown (selectlist) with values coming from a restful service. These values are different for each row.
I should be able to select one value from this list (dropdown) and it should persist the value in the cell.
I would be glad if someone could help with this problem.
this.productColumns = [
{
id: 'statusid',
name: 'Status',
field: 'statusid',
width: 65,
sortable: true
},
{
id: 'grade',
name: 'Grade',
field: 'grade',
width: 80,
sortable: true
},
{
id: 'position',
name: 'Position',
field: 'originalPosition',
width: 80,
sortable: true
},
{
id: 'tyresize',
name: 'Tyre Size',
field: 'tyreSize',
editable: true,
width: 140,
sortable: true
},
{
id: 'tyredetail',
name: 'Tyre Detail',
field: 'tyredetail',
editable: true,
width: 125,
editor: this.selectRangeEditor
}
]
selectRangeEditor: function (args) {
var $select = $("");
var defaultValue = "";
var scope = this;
this.init = function () {
var tyreOptionsList = new TyreOptionsModel(args.item.id);
tyreOptionsList.deferred.done(function () {
var opt_values = tyreOptionsList.toJSON();
var count = 0;
for (var cnt in opt_values) {
if (opt_values.hasOwnProperty(cnt)) {
count++;
}
}
option_str = ""
var i ;
for (i = 0; i < count-1; i++) {
val = opt_values[i].tyreOptionId;
txt = opt_values[i].tyreDetail;
option_str += "<OPTION value='" + val + "'>" + txt + "</OPTION>";
}
$select = $("<SELECT tabIndex='0' class='editor-select'>" + option_str + "</SELECT>");
$select.appendTo(args.container);
$select.focus();
});
};
this.destroy = function () {
$(args.container).empty();
};
this.focus = function () {
$select.focus();
};
this.serializeValue = function () {
return $select.val();
};
this.applyValue = function (item, state) {
item.attributes[args.column.field] = state;
};
this.loadValue = function (item) {
defaultValue = item.attributes[args.column.field];
$select.val(defaultValue);
};
this.isValueChanged = function () {
return ($select.val() != defaultValue);
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
this.init();
return $select.val();
}
Did you see my answer to this question ?
If you are able to get the options from the rest service for each row while generating the page, you can just use my solution at the client side ...
As I understand from you comment, the problem is how to postback the changes made in the grid after the user changed some fields ...
I solved this by adding the following piece of code, notice the JS code for the form submit, handle this incoming data at the server side, to save it using the RESTfull service.
<div id="myGrid" style="width:90%;height:250px;"></div>
<form action="" method="POST">
<input id="save_grid_changes" disabled="disabled" type="submit" value="Save changes to {{obj_type}}(s)">
<input type="hidden" name="obj_type" value="{{obj_type}}">
<input type="hidden" name="data" value="">
</form>
<script>
$(document).ready(function() {
grid = new Slick.Grid($("#myGrid"), griddata, columns, options);
$("form").submit(
function() {
// commit the last edit ...
grid.getEditController().commitCurrentEdit();
grid.resetCurrentCell();
$("input[name='data']").val( $.toJSON(griddata) );
// ("input[name='data']").val($.param(data));
});
});
</script>

Categories

Resources