Assigning dynamic value to a global variable in kendo grid column template - javascript

Ok now I have this Kendo Grid code:
var ds = [
{ "ID" : 1, "attach" : "true", "attachment" : "http://www.google.com" },
{ "ID" : 2, "attach" : "false", "attachment" : "" },
{ "ID" : 3, "attach" : "true", "attachment" : "http://www.wikipedia.com" },
{ "ID" : 4, "attach" : "false", "attachment" : "" }
];
var $value = "asd";
var grid = $("#grid").kendoGrid({
dataSource: ds,
columns: [
{ field: "ID", Title: "ID", filterable: false, sortable: false, hidden: false },
{ field: "attach", Title: "Attached?", filterable: false, sortable: false, hidden: false},
{
title: "Attachment Link",
template: '#if(attachment != ""){' +
'$value = attachment' +
'#<input type="button" class="info" value="IT WORKS" />' +
'#}else{#' +
'<label>NOPE</label>' +
'#}#',
headerTemplate: "<label> Attachment </label>",
sortable: false,
filterable: false,
width: 100
}
]
}).data("kendoGrid");
//this is where I have been playing around trying to get the value. its not working. Shocker :D
//I changed this part frequently, this is just the latest form I got it in.
$(".info").on("click", function() {
var row = $(this).closest("tr");
var item = grid.dataItem(row);
var show = $value;
alert("The item is:" + show);
});
where I check if a column of a row has any non empty value or not, and if so I place a button there.
When I try to assign the value to attachment, ('value = attachment' part) I'm getting undefined as a result, but if I enclose attachment like this:
'#if(attachment != ""){#' +
'#= attachment#' +
'<input type="button" class="info" value="IT WORKS" />'
'#}else{#' +
'<label>NOPE</label>' +
'#}#',
I can print the actual link assigned to it. How can I get the value of the attachments (individually, not as a list or array or sth) when I click the button associated with it?
Here is the fiddle: https://jsfiddle.net/phyrax/zz1h65f5/
Thanks in advance!

Kendo grid column template is a template for HTML content.
If you want to place some element in html code, you should use template. As I see, you want to execute JS code inside this template. To do this you should define <script> $value = #= attachment# </script> in your template.
Other question is what you want to do, because when you do something like this, it is executed for each row during page load. So the value of $value will be always set to last row.
EDIT to first comment:
You should consider to define template as
<input type="button" class="info" value="IT WORKS" onclick="setAttachment('#= attachment#')" />
and in global JS code define function
function setAttachment(attachmentValue)
{
$value = attachmentValue;
}
This is more proper way to solve this task. Make action on click trigger, not immediately.

Related

Binding array of object to Kendo grid popup multiselect

I'm trying to bind an array of id-value pairs to a kendo grid popup editor.
Got everything to work for creating a new record. Popup editor loads the custom editor and successfully submits the data to the controller.
The problem is when I try to edit records. The records displays properly in the row, but when I try to edit it, the multiselect does not hold the values.
Grid Markup
$("#ProjectSites-SubContract-grid").kendoGrid({
dataSource: {
type: "json",
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
DateOfContract: { type: 'date', editable: true },
DateOfCompletion: { type: 'date', editable: true },
AmountOfContract: { type: 'number', editable: true },
Contractor: { defaultValue: { id: "", name: "" } }
}
}
},
},
columns: [
{
field: "ScopeOfWork",
title: "Scope of Work",
template: "#=parseScopeOfWork(ScopeOfWork)#",
editor: scopeOfWorkEditor
},
]
});
});
Scope of Work editor
function scopeOfWorkEditor(container, options) {
$('<input data-text-field="name" data-value-field="id" data-bind="value:ScopeOfWork"/>')
.appendTo(container)
.kendoMultiSelect({
dataSource: {
data: [
#foreach (var scopeOfWork in Model.AvailableScopeOfWork)
{
<text>{ id : "#scopeOfWork.Value", name : "#scopeOfWork.Text" },</text>
},
]
}
});
parseScopeOfWork -
this method guys iterates through the object list and concats the name.
function parseScopeOfWork(scopeOfWork) {
var result = "";
for (var i = 0; i < scopeOfWork.length; i++) {
result += scopeOfWork[i].Name;
if (i < scopeOfWork.length - 1)
{
result += ", <br/>";
}
}
return result;
}
Here's a screenshot:
You're binding the SpaceOfWork to the new widget, but how that widget knows your Model ? I mean, just using data-bind doens't binds the model to the widget, it can't figure that by itself. I have two suggestions:
Set the value in the widget's initialization:
.kendoMultiSelect({
value: options.model.ScopeOfWork
Demo
Bind the model to the widget for good:
let $multiSelect = $('<input data-text-field="name" data-value-field="id" data-bind="value:ScopeOfWork"/>');
kendo.bind($multiSelect, options.model);
$multiSelect
.appendTo(container)
.kendoMultiSelect({ ...
Demo
Note: Edit the category cell in both demos to see the changes.

How to delete a row in dojo EnhancedGrid using row index not by using selection

Trying to find an answer to remove a row for dojo EnhancedGrid based on the row index.
Please find the EnhancedGrid.
var dataStore = new ObjectStore({objectStore: objectStoreMemory});
// grid
grid = new EnhancedGrid({
selectable: true,
store: dataStore,
structure : [ {
name : "Country",
field : "Country",
width : "150px",
reorderable: false,
editable : true
}, {
name : "Abbreviation",
field : "Abbreviation",
width : "120px",
reorderable: false,
editable : true
}, {
name : "Capital",
field : "Capital",
width : "100%",
reorderable: false,
editable : true
}, {
label: "",
field: "Delete",
formatter: deleteButton
}],
rowSelector: '20px',
plugins: {
pagination: {
pageSizes: ["10", "25", "50", "100"],
description: true,
sizeSwitch: true,
pageStepper: true,
gotoButton: true,
maxPageStep: 5,
position: "bottom"
}
}
}, "grid");
grid.startup();
And the Delete Button Script is here:
function deleteButton(id) {
var dBtn1 = "<div data-dojo-type='dijit/form/Button'>";
var dBtn2 = "<img src='delete.png' onclick='javascript:removeItem()' alt='" + id + "'";
dBtn = dBtn1 + dBtn2 + " width='18' height='18'></div>";
return dBtn;
}
Here is my Question: Each row will have a delete button at the end, On click of this button the same row should be deleted.
Can anybody tell me how to delete a row based on row index?
If you want to add (remove) data programmatically, you just have to
add (remove) it from the underlying data store. Since DataGrid is
“DataStoreAware”, changes made to the store will be reflected
automatically in the DataGrid.
https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
dojox/grid has a property selection and method getSelected() to get selected items. In example from documentation it's implemented in following way:
var items = grid5.selection.getSelected();
if(items.length){
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
// Delete the item from the data store:
store3.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
Hope it will help.
Here is the solution. The sequence of methods that will run onClick of a button are removeItem() and onRowClick event
1> Set the "deleteButtonFlag" on click of a button.
function removeItem() {
deleteButtonGFlag = true;
}
2> Remove item
dojo.connect(grid, "onRowClick", function(e) {
if (deleteButtonGFlag) {
dataStore.fetch({
query: {},
onComplete: function(items) {
var item = items[e.rowIndex];
dataStore.deleteItem(item);
dataStore.save();
deleteButtonGFlag = false;
}
});
}
});

Error in kendo grid - grid.select is not a function why?

I have a kendoDropDown list as a cell in my grid. I am calling the kendDropDownList using the editor command of kendo grid ("editor"). I need to pass selected value of selected row to kendoDropDownList as a parameter in order to server reply back only with filtered list as my kendoDropDownList . Please see my below example
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
columnMenu:true,
filterable:true,
height: 550,
reorderable: true,
columnReorder: function(e) {
console.log(e.column.field, e.newIndex, e.oldIndex);
},
toolbar: ["create","excel","save", "cancel" , { template: kendo.template($("#template").html()) } , { template: kendo.template($("#clearFilterTemplate").html()) } , { name: "create", text: "Add New Employee" }],
excel: {
fileName: "Kendo UI Grid Export.xlsx",
proxyURL: "excelExport",
filterable: true,
allPages: true
},
editable: "inline" , //editable: true,
columns: [
{ field: "fileNo" , title:"File No" , width: 80 },
{ field: "jobNo" , title:"Job No" , width: 80 },
{ field: "discipline" , title:"Discipline" , width: 80 },
{ field: "moduleNo" ,title:"Module", width: 100},
{ field: "description",title:"Title",editor: descriptionDropDownEditor, width: 150},
{ field: "documentNo",title:"Document No", width: 150 },
{ field: "remarks",title:"Remarks" , width: 150 } ,
{ command: ["edit","destroy"], title: " ", width: "250px" }
]
});
function descriptionDropDownEditor(container, options) {
// here is the error grid.select is not a function why ?
var selectedItem = grid.dataItem(grid.select());
var selectedJobNo = selectedItem.jobNo ;
alert("selectedJobNo :"+selectedJobNo );
$('<input required name="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataTextField: "text",
dataValueField: "value",
filter: "contains",
dataSource: {
dataType: "json",
transport: {
// I need to pass the selected jobNo in order to get the only aprropriate descrption for that jobNo
// each row job has description and I don't want to show all the description for all jobs , I need only for that row jobNo
read: "getDescriptionForEachDocumentIndex?selectedJobNo"+selectedJobNo
}
}
});
}
once the row of grid in edit mode I need to pass the selected row jobNo to kendoDropDownList in order to respond back with only releated description for that jobNo. The problem is i can not call grid in the edit mode and use the function grid.select() . what to do in this case ?
Well, that is easy. The second parameter of your editor function has a property called model, which is the dataItem of the current row user is editing. So in your case, I supose this would work:
function descriptionDropDownEditor(container, options) {
var selectedItem = options.model;
But, to answer your question, you can't access the select() method because grid is not a Kendo Grid object, it is in fact the #grid element. You can either add .data("kendoGrid") at the end of the widget initialization:
$("#grid").kendoGrid({ ... }).data("kendoGrid");
Or call it inside the function:
function descriptionDropDownEditor(container, options) {
var gridWidget = $(grid).data("kendoGrid");
var selectedItem = gridWidget.dataItem(gridWidget.select());

How to make "add new record" represent field as checkbox - Kendo Grid

I am trying to add a new record to a kendo grid (only using client side javascript) and I can only get all the fields represented as text fields.
One of the fields however is actually a boolean and I would like it to be represented as a check box instead. Does anyone know how to do this?
Can anyone please help? Any help would be greatly appreciated.
UPDATED with code below. Also I tried the template suggestion but this is not working when I click on the Add New Record button at the top of the grid. I get a JavaScript error "primary is not defined"
$("#phoneGrid").kendoGrid({
columns: [
{
field: "type",
title: "Type"
},
{
field: "primary",
title: "Primary",
template: "<input type=\"checkbox\" #= primary ? checked='checked' : '' #/>"
},
{
field: "number",
title: "Number"
},
{ command: ['edit'], title: ' ' }
],
editable: "inline",
dataSource: {
data: patientDetailUpdateViewModel.phones,
schema: {
model: { id: "id" }
}
},
toolbar: ['create'],
save: function (e) {
//alert("Save Event Triggered");
if (e.model.isNew()) {
phone = new Phone();
//Give the phone an id to uniquely identify it, but one which would signify a new phone instance (negative phone instance).
phone.id = patientDetailUpdateViewModel.phones.length * -1;
e.model.id = phone.id;//So isNew() will return false on subsequent calls.
phone.type = e.model.type;
phone.primary = e.model.primary;
phone.number = e.model.number;
patientDetailUpdateViewModel.phones.push(phone);
//alert("isNew() = true");
}
}
});
You can use template for column definition:
{
field: "ColumName",
template: '<input type="checkbox" #= Column? checked="checked" : "" # disabled="disabled" ></input>'
}
EDIT:
Try to define data source model (http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-schema.model) like below, but according to your data types in source:
schema: {
model: {
id: "ProductID",
fields: {
type: {
type: "string"
},
UnitPrice: {
type: "number"
}
}
}
}

kendo multiselect refresh list

i am try kendo multiselect tab remove when click on button and again this remove option in come to select.
i have done this code
Close Oranges
<script>
$("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
tagTemplate: "<span class='mitesh12' entity_id ='${data.id}' path ='${data.name}' >" + '#: data.name #' + "</span>",
});
function closeOrange(e){
$("span[entity_id='2']").parent().parent().remove();
}
</script>
this is jsfiddle and i want like this Like
here i am try to remove orange tag and after remove this again i am able to select this orange
help me out this
thanks.
You did not follow the same approach than your second link.
Define the HTML as:
<select id="multiselect" multiple="multiple"></select>
<button id="oranges" class="k-button">Close Oranges</button>
And this code for creating the multiselect:
var multi = $("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
tagTemplate: "<span class='mitesh12' entity_id ='${data.id}' path ='${data.name}' >" + '#: data.name #' + "</span>",
}).data("kendoMultiSelect");
The button handler for removing the value is:
$("#oranges").on("click", function(e) {
// List of values to remove (only the ones with id = 2)
var subtract = [2];
var values = multi.value().slice();
values = $.grep(values, function(a) {
return $.inArray(a, subtract) == -1;
});
// Filter out everything
multi.dataSource.filter({});
// Now add the remaining values.
multi.value(values);
});
You can see it here : http://jsfiddle.net/OnaBai/9WfGA/23/

Categories