How to remove all items from a kendoListBox - javascript

I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});

Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo

Related

Creation one or several new tags in select2 dropdown field

I used library select2 for dropdown field and for creation new tag - option "createTag", code looks that -
function create_tag_custom (params) {
var term = $.trim(params.term);
var term_id = term;
if (term === '') {
return null;
}
$.ajax ({
'delay': 250,
'async': false,
'type': 'GET',
'url': "{% url 'my_url' %}",
'data': {'q': term},
'success': function(data) {
if (data["result"]) {
term_id = '' + data['result'][0] + '_';
term = '' + data['result'][1];
}
}
});
return {
id: term_id,
text: term,
newTag: true
}
}
$('#id_smart_source').select2({
width: "100%",
allowClear: true,
placeholder: "Select a prefix",
tags: true,
multiple: true,
createTag: create_tag_custom,
tokenSeparators: [',',';'," ", ", "],
});
and it's works correct, new one tag is created in dropdown. But I want to create one tag OR multiple tags at once. So that the code can work like this, for example -
function create_tag_custom (params) {
var term = $.trim(params.term);
var term_id = term;
if (term === '') {
return null;
}
var results = null;
$.ajax ({
'delay': 250,
'async': false,
'type': 'GET',
'url': "{% url 'my_url' %}",
'data': {'q': term},
'success': function(data) {
if (data["result"]) {
results = $.map(data, function (item) {
return {
text: item[0],
id: item[0]
}
})
} else {
results = {
id: term_id,
text: term,
newTag: true
}
}
}
});
return results
}
Can select2 return one or more new tags?

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

csrf token set as post parameter while deleting action in Jtable (Jquery )

Hi i'm trying to add csrf token in post while deleting record in jtable its not working but listAction & updateAction is working fine.
My Code snippets :-
$(document).ready(function () {
$('#main-content').jtable({
title: ' Data',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
actions: {
listAction:"${pageContext.request.contextPath}/mycontroller/all" ,
// createAction:"${pageContext.request.contextPath}/mycontroller/create",
updateAction:"${pageContext.request.contextPath}/mycontroller/edit",
deleteAction:"${pageContext.request.contextPath}/mycontroller/delete"
},
fields: {
code: {
title:'Code',
width: '25%',
key: true,
edit:true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="code" value="' + data.value + '"/>';
}
},
},
name: {
title: 'Name',
width: '25%',
create:true,
edit:true
},
craetedTs: {
title: 'Created',
width: '25%',
edit:false
},
modifiedTs: {
title: 'mdate',
width: '25%',
edit:true,
input: function (data) {
if (data.value) {
mdate='';
var date = new Date();
var options = {
year: "numeric", month: "2-digit",
day: "2-digit", hour: "2-digit", minute: "2-digit" ,second:"2-digit"
};
today=date.toLocaleTimeString("en-us", options);
today=today.replace(',', '');
return '<input type="text" readonly class="jtable-input-readonly" name="modifiedTs" value="' + today + '"/>';
}
}
},
_csrf: {
visibility: 'hidden',
edit:true,
input: function (data) {
return '<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />';
}
}
}
});
$('#main-content').jtable('load',{'${_csrf.parameterName}' : '${_csrf.token}'});
//Delete selected
$('#DeactiveID').button().click(function () {
var $selectedRows = $('#main-content').jtable('selectedRows');
$('#main-content').jtable('deleteRows', $selectedRows);
});
});
Even i tried for deleting code bellow:-
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
data: '${_csrf.parameterName}' + "=" +'${_csrf.token}' ,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
But when i checked delete action url the entire method was reflecting
Add meta elements to the page you are invoking the ajax method from
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
And make this change to your deleteAction
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
beforeSend: function (request)
{
request.setRequestHeader(header, token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
If somebody is still wondering, Lalit got me going in the right direction, but my final solution is this:
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
This solves the issue with passing csrf, or any additional data, for that matter, in jTable AJAX delete call. As for the other cases. Putting this right after you include the jTable js foxes the initial load:
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
And then there is this hidden field to add to the field list:
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
Here is my code as a full example:
<!-- Include jTable script file. -->
<script src="{{site.uri.public}}/jtable/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
var csrf_token = $('meta[name=csrf_token]').attr("content");
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var csrf_token = $('meta[name=csrf_token]').attr("content");
$("#PrizesTableContainer").jtable({
title: 'Prizes',
actions: {
listAction: 'prizes/get',
createAction: 'prizes/create',
updateAction: 'prizes/update',
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
id: {
key: true,
list: false
},
machine_name: {
title: 'Machine name',
width: '10%'
},
reel1: {
title: 'Reel1',
width: '15%'
},
reel2: {
title: 'Reel2',
width: '15%'
},
reel3: {
title: 'Reel3',
width: '15%'
},
payout_credits: {
title: 'Payout credits',
width: '15%'
},
payout_winnings: {
title: 'Payout winnings',
width: '15%'
},
probability: {
title: 'Probability',
width: '15%'
},
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
}
});
$("#PrizesTableContainer").jtable('load');
});
</script>

Kendo Scheduler, programmatically set values not updating dataModel

Kendo Scheduler via javascript
Custom Edit Template
Edit Event -> programmatically setting a value on custom template controls
Value shows in control, not included in dataModel
I am implementing a Kendo Scheduler via javascript. I am using a custom edit template because there are several editable fields which are not native to the scheduler. One such field uses a kendo dropdownlist. I have subscribed to the edit event and in this event I get a handle on the dropdown and set its value. The UI element correctly shows the value I have set but when I save the scheduler the dropdownlist value is not included in the JSONified dataModel which I pass off to a CRUD handler. If I manually select an option from the dropdownlist it is included. I called the change event of the dropdownlist for giggles after the programmatic setting of its value. Still nothing. I tried this with textboxes, multiselections, numerictextboxes... they all fail to register their programmatically set values with the model.
Ideas? Thanks.
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2015/4/14"),
views: [
"day",
{ type: "workWeek", selected: true, showWorkHours: true },
"week",
"month"
],
allDayEventTemplate: $("#allDay-template").html(),
eventTemplate: $("#event-template").html(),
edit: function (e) {
var location = e.container.find("[id=location]");
location.kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: GetLocations,
filter: "contains",
suggest: true
});
var taskReminder = e.container.find("[id=AddTaskReminder]");
taskReminder.kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
var wnd = $(e.container).data("kendoWindow");
wnd.setOptions({
width: 800,
height: 600
});
var clientID = $("#clientID");
var ClientID = e.container.find("[id=ClientID]").data("kendoDropDownList");
if (clientID.val() != "All") {
ClientID.enable(false);
}
var Priority = $(e.container.find('[data-bind="value: Priority"]')).data("kendoDropDownList");
if (e.event.isNew()) {
if (clientID.val() != "All") {
ClientID.value(clientID.val());
e.container.find("[id=ClientID]").change();
}
var workerID = $("#workerID");
var WorkerID = e.container.find("[id=workers]").data("kendoMultiSelect");
if (workerID.val() != null) {
WorkerID.value(workerID.val());
e.container.find("[id=workers]").change();
}
Priority.value(2);
(e.container.find('[data-bind="value: Priority"]')).change();
}
var taskName = e.container.find("[id=taskName]");
taskName.kendoComboBox({
dataSource: GetTaskTypes,
dataTextField: "text",
dataValueField: "value",
filter: "contains",
suggest: true
});
var isAllDay = $(e.container.find('[id=isAllDay]'));
var StartDateTime = $(e.container.find('[id=startdatetime]')).data("kendoDateTimePicker");
var EndDateTime = $(e.container.find('[id=enddatetime]')).data("kendoDateTimePicker");
var DueDateFirm = $(e.container.find('[id=DueDateFirm]'));
var Reminder = $(e.container.find('[id=AddTaskReminder]')).data("kendoNumericTextBox")
var TaskComment = $(e.container.find('[id=TaskComment]'));
taskName.change(function () {
$("#TaskTypeName").val($(e.container.find("[id=taskName]")).data("kendoComboBox").text());
if ($(e.container.find("[id=taskName]")).data("kendoComboBox").select() != "-1") {
if (confirm("Apply task type defaults (overriding previous values)?")) {
$.ajax({
type: "GET",
cache: false,
url: "/home/schedule/remotetasks.asp?Action=GetDefaultTaskTypeValues&DefaultTask=" + $(taskName).val(),
success: function (data) {
DS = JSON.parse(data);
Priority.value(DS[0].Priority);
if (DS[0].AllDayEvent == "True") {
isAllDay.prop("checked", true);
}
else {
isAllDay.prop("checked", false);
if (DS[0].DefaultStartTime != "") {
var d = new Date(StartDateTime.value());
d.setHours(DS[0].DefaultStartHour);
d.setMinutes(DS[0].DefaultStartMinute);
StartDateTime.value(d);
}
if (DS[0].DefaultEndTime != "") {
var d = new Date(EndDateTime.value());
d.setHours(DS[0].DefaultEndHour);
d.setMinutes(DS[0].DefaultEndMinute);
EndDateTime.value(d);
}
}
isAllDay.change();
Reminder.value(DS[0].DefaultReminderMinutes);
TaskComment.val(DS[0].TaskComment);
}
});
}
}
});
},
save: function (e) {
if (e.container != null) {
// AssignedTaskName req val
// Dates req val
var isAllDay = e.container.find("[id=isAllDay]");
var startdatetime = e.container.find("[id=startdatetime]");
var startdate = e.container.find("[id=startdate]");
var enddatetime = e.container.find("[id=enddatetime]");
var startdatereq = e.container.find("[id=startdatereq]");
var enddatereq = e.container.find("[id=enddatereq]");
var isAllDay = $(startdate).is(":visible");
if (isAllDay) {
if ($(startdate).val() == "") {
//alert('invalid startdate');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdate');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
}
else {
if ($(startdatetime).val() == "") {
//alert('invalid startdatetime');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdatetime');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
if ($(enddatetime).val() == "") {
//alert('invalid enddatetime');
e.preventDefault();
if ($(enddatereq).hasClass('hidden'))
enddatereq.removeClass('hidden');
}
else {
//alert('valid enddatetime');
if (!$(enddatereq).hasClass('hidden'))
enddatereq.addClass('hidden');
}
}
}
},
editable: {
template: kendo.template($("#customEditorTemplate").html())
},
moveEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
resizeEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
dataSource: {
batch: true,
sync: function () {
this.read();
},
transport: {
create: {
url: "/home/schedule/remotemanagecalendar.asp?Action=create",
dataType: "json"
},
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=read",
dataType: "json"
},
update: {
url: "/home/schedule/remotemanagecalendar.asp?Action=update",
dataType: "json"
},
destroy: {
url: "/home/schedule/remotemanagecalendar.asp?Action=destroy",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation === "read") {
var scheduler = $("#scheduler").data("kendoScheduler");
var result = {
start: scheduler.view().startDate(),
end: scheduler.view().endDate(),
clientid: $("#clientID").val(),
workerid: $("#workerID").val(),
taskstatus: $("#taskStatus").val()
}
return { models: kendo.stringify(result) };
}
else if (operation === "create" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation === "update" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "id",
fields: {
id: { from: "AssignedTaskID", type: "number" },
taskTypeID: { from: "TaskTypeID", type: "int" },
title: { from: "AssignedTaskName", type: "string" },
start: { from: "StartDateTime", type: "date", validation: { required: true } },
end: { from: "EndDateTime", type: "date" },
isAllDay: { from: "isAllDay", type: "boolean" },
dueDateFirm: { from: "DueDateFirm", type: "boolean" },
reminderMinutes: { from: "ReminderMinutes", type: "int" },
ClientID: { from: "ClientID", type: "int" },
Priority: { from: "Priority", type: "int" },
workers: { from: "Workers", nullable: true },
TaskComment: { from: "TaskComment", type: "string" },
locationid: { from: "LocationID", type: "string" }
}
}
}
}
});
});
var GetTaskTypes = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddTaskTypes",
dataType: "json"
}
}
});
var GetClientIDs = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddClients",
dataType: "json"
}
}
});
var GetPriorities = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetPriorities",
dataType: "json"
}
}
});
var GetAddWorkers = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddWorkers",
dataType: "json"
}
}
});
var GetLocations = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetLocations",
dataType: "json"
}
}
});
$("#AddTaskReminder").kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
I found the answer
edit: function(e) {
e.event.set('modelFieldName', 'value');
}
This sets it on the UI element as well as updates the dataModel. Hope it helps the next poor sap.

Get values from a table cell

I have this part of code:
$.ig.loader(function () {
$("#grid2").igGrid({
autoGenerateColumns: false,
renderCheckboxes: true,
columns:[
{ headerText: "#", key: "#", dataType: "number", width: "40%"},
{ headerText: "filename", key: "fieldname", dataType: "image", width: "40%"},
{ headerText: "X", key: "x", dataType: "number", width: "40%"},
{ headerText: "Y", key: "y", dataType: "number", width: "40%"},
{ headerText: "Z", key: "z", dataType: "number", width: "40%"},
],
//dataSource: data,
height: "400px",
width: "100%",
features:[
{
name: "Filtering",
allowFiltering: true,
type: "local"
},
{
name: "Selection",
mode: "row"
},
{
name: "Updating",
enableAddRow: false,
editMode: "row",
// event raised after end row editing but before dataSource was updated
editCellEnding: function (evt, ui) {
// get cell’s checkbox value when it is changed
if (ui.update) {
if (ui.columnKey === "nid") {
logEvent("editCellEnded event fired. Column Key = " +
ui.columnKey + "; Row Index = " +
ui.rowID + "; Cell Value = " +
ui.value + "; Update = " +
ui.update);
}
}
},
enableDeleteRow: false,
columnSettings: [
{
columnKey: "#",
},
{
columnKey: "fieldname",
},
{
columnKey: "x",
},
{
columnKey: "y"
},
{
columnKey: "z"
}]
}
]
});
$.ajax({
type: "POST",
url: "http://cmsdemo.trueoffice.com/feature-json2",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$("#grid2").igGrid({
dataSource: data
});
}
});
$("#grid2").live("iggridupdatingdatadirty", function (event, ui) {
$("#grid2").igGrid("commit");
return false;
});
// show the raised event
function logEvent(message) {
var evntWrap = $("#eventList");
$(evntWrap).append("<div>" + message + "<div>");
$(evntWrap).prop("scrollTop", $(evntWrap).prop("scrollHeight"));
}
});
//Functions
function Filter() {
var columnSettings = $("#grid1").igGridFiltering("option", "columnSettings");
var expr = $("#filterExpr").val(),
condition = $("#cond_list").val(),
filterColumn = $("#filterColumn").val();
$("#grid1").igGridFiltering("filter", ([{fieldName: filterColumn, expr: expr, cond: condition}]));
}
function SetConditions() {
var filterColumn = $("#filterColumn").val();
$("#cond_list option:selected").removeAttr("selected");
if (filterColumn === "title" || filterColumn === "nid") {
$("#cond_list .stringCondition").attr("disabled", "disabled");
$("#cond_list .numberCondition").removeAttr("disabled").eq(0).attr("selected", "selected");
}
else {
$("#cond_list .stringCondition").removeAttr("disabled").eq(0).attr("selected", "selected");
$("#cond_list .numberCondition").attr("disabled", "disabled");
}
}
function buttonClickHandler(buttonId) {
alert("Button with id " + buttonId + " was clicked");
}
and this part of code
<script>
var layer1 = document.getElementById('layer1');
ctx1 = layer1.getContext('2d');
var item1 = new Image();
item1.src = "<?php echo $base_url;?>/themes/bartik/images/sheep.png";
item1.addEventListener("load", function() {
ctx1.clearRect(0,0,1024,768)
ctx1.drawImage(item1,x,y)}, false); //how to get values from a table row?
</script>
My question is: How I can get values from a first row of table and send it to ctx1.drawImage(item1,x,y).
I can do copy/paste rest of the code if it be necessary.

Categories