Kendo UI Grid get id of current element javascript - javascript

i m using Kendo UI apsnet and i have a Gird with autocomptele as template in 3rd column and i want send data using javascript function "onAutoCompleteX", in this function i want to get id of active autocomplete to send text as parametere to action "GetArticle" but my probleme is how get this id, tried many methods always i get "undefined" or error
#using KendoUIMvcApplication2.Areas.Gescom.Models.Achat
<style>
.k-widget .templateCell
{
overflow: visible;
}
</style>
<script>
function initMenus(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
function onAutoCompleteSelectX(e) {
var dataItem = this.dataItem(e.item.index());
var url = '#Url.Action("GetArticle", "Fiche")';
$.ajax({
url: url,
data: { code: dataItem.Code }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
if (data == null)
document.getElementById('labelx').innerHTML = "null";
else
document.getElementById('labelx').innerHTML = data.Code;
},
error: function () {
document.getElementById('labelx').innerHTML = "error";
}
});
}
function onAutoCompleteX() {
var currentId = $(this).attr('id');
//var currentId = $(this).id;
//document.getElementById('labelx').innerHTML = $(this).className; //$obj.attr('id');
return {
text: document.getElementById(currentId).value
//text: $("#id_of_another_autocomplete").val() works fine when i set static id manually
};
}
</script>
<div class="lines-tab-doc">
#(Html.Kendo().Grid<LineAppelOffre>()
.Name("grid-lines-doc")
// Declare grid column
.Columns(columns =>
{
// Cretae all the columns base on Model
columns.Bound(l => l.Document);
columns.Bound(l => l.LigneOriginale);
columns.Template(l => { }).Title(#Resources.Resource.Article)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(
Html.Kendo().AutoComplete()
.Name("Article")
.HtmlAttributes(new { id = "#=LigneOriginale#", style = "width:100%;" })
.DataTextField("Code")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetArticles", "Fiche").Data("onAutoCompleteX");
})
.ServerFiltering(true);
})
.Events(e => { e.Select("onAutoCompleteSelectX"); }).ToClientTemplate().ToHtmlString()
);
columns.Bound(l => l.Fournisseur);
columns.Bound(l => l.RefArtFrs);
// Edit and Delete button column
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
})
.Events(ev => ev.DataBound("initMenus"))
// Declare ajax datasource.
// CRUD operation are wired back to ASP MVC Controller/Action e.g. HomeController, GetAll
// Set the model Id
.DataSource(datasoure => datasoure.Ajax()
.Model(model =>
{
//model.Id(l => l.Document);
model.Id(l => l.LigneOriginale);
})
.Read(read => read.Action("LinesAppelOffre_Read", "Achat"))
.Create(create => create.Action("LinesAppelOffre_Add", "Achat"))
.Update(update => update.Action("LinesAppelOffre_Update", "Achat"))
.Destroy(delete => delete.Action("LinesAppelOffre_Delete", "Achat"))
.PageSize(10)
)
// Add tool bar with Create button
.ToolBar(toolbar => toolbar.Create())
// Set grid editable.
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable(scr=>scr.Height(327))
.Sortable()
.Selectable()
.Navigatable()
.Pageable(pageable =>
{
pageable.Refresh(true);
pageable.PageSizes(true);
pageable.Messages(msg => msg.Empty(null));
})
)
</div>

You can get your AutoComplete id like that:
function onAutoCompleteX(e) {
var currentId = e.sender.element.attr('id');
...
}
But I'm not sure if you have explicity set name as "Article" .Name("Article") you will not always get "Artilcle" as id, even if you set it using .HtmlAttributes property.
If so, just try to use different attribute then id and get is same way.

i used document.activeElement
Browser compatibility
Chrome 2
Firefox (Gecko) 3.0
Internet Explorer 4
Opera 9.6
Safari 4.0

Related

Copy kendo grid item containing xml and Json to clipboard with formatting through javascript

I'm stuck in a problem, I have a grid that contains an item which can contain Json or XML. I need this data to be copied on the clipboard. Below is my code that i'm using to copy the content. It's basically setting the value of a hidden field and then copying the data from that field to the clipboard. What I'm stuck with is the data is being copied as a string and i want to have it copied in proper JSON formatting is there a way to achieve this? I have tried and none of these work.
JSON.stringify(jsObj, null, "\t");
JSON.stringify(jsObj, null, 4);
Below is the my copy function.
function CopyData(e) {
var tr = $(e.target).closest("tr");
var newItem = this.dataItem(tr);
$('#ContentTypeField').val(newItem.Content);
var copyText = document.getElementById("ContentTypeField");
copyText.type = 'text';
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
copyText.type = 'hidden';
}
and my grid
#(Html.Kendo().Grid<App.Models.ViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID).Width(240).Hidden(true);
columns.Bound(p => p.Name).Width(280);2
columns.Bound(p => p.Description).Width(440);
columns.Command(command => {command.Custom("Content").Click("CopyData"); }).Width(150);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("Add");
})
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("Content.cshtml"))
.Pageable(pager => pager
.Input(true)
.Numeric(true)
.Info(true)
.PreviousNext(true)
.Refresh(true)
.PageSizes(true)
)
.Sortable()
.Reorderable(reorder => reorder.Columns(true))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.Events(events => events.Error("error_AppSetting"))
.Model(model =>
{
model.Id(p => p.ID);
model.Field(s => s.Name);
model.Field(s => s.Description);
})
.Read("Read", "App")
.Update(c => c.Action("Update", "App"))
.Destroy(c => c.Action("Delete", "App"))
.Create(c => c.Action("Create", "App"))
)
)
I used clipboard API to achieve this. It takes the text as parameter since in the previous method I was setting value of a hidden field and then copying it to the clipboard which changed the formatting. Below is the code on how I did it.
navigator.clipboard.writeText(grid.fields.Content).then(function () {
alert('successfully copied!');
},
function () {
alert ('Copy to clipboard failed');
});

How to refresh a kendo ui grid inside a partial view without reloading the entire page?

Good day,
I am having a tough time refreshing just the kendo grid that is placed inside a partial view. Take a look at the code I am currently using in my partial view:
#model IEnumerable<TelerikMvcAscernAdmin2.Models.ConnectionViewModel>
#(Html.Kendo().Grid(Model).Name("id").Sortable().Columns(c => {
c.Bound(p => p.SystemId);
c.Bound(p => p.Host);
c.Bound(p => p.Port);})
.DataSource(datasoure =>datasoure.Server().PageSize(25).Sort(sort=>{sort.Add(c => c.Host).Ascending(); })
).Filterable()
.Pageable(p => p.PageSizes(new int[] { 25, 35, 40 })
.Refresh(true)).Groupable().Sortable().Scrollable(s => s.Height("200px")).RowAction(row => {
if (row.DataItem.Port == 0) row.HtmlAttributes["style"] = "background:red"; }).HtmlAttributes(new { style = "width: 800px;" }) )
<script> $(document).ready(function () {
var refId = setInterval(function () {
var grid = $("#id").data("kendoGrid");
grid.dataSource.read();
}, 40000);
}); </script>
As you can see, I am using a server side function so that I can auto-refresh this grid. I have tried switching it to an Ajax function, but when I do that my grid can't be refreshed.
I am rendering this partial view inside my Home view, as shown below:
#Html.Action("EngineConnection", "GatewayConnections")
Also, take a look at my action controller method, I am returning all my data to a partial view:
public ActionResult EngineConnection()
{
var gatewayConnections = GatewayConnections.GetAllConnections();
var agents = Agent.RetrieveAgents();
var connectionViewModels = (from agent in agents.Where(a => a.Active)
join gatewayConnection in gatewayConnections on agent.SystemId equals gatewayConnection.ClientId into
agentConnections
from agentConnection in agentConnections.DefaultIfEmpty()
select
new ConnectionViewModel
{
SystemId = agent.SystemId,
Host = (agentConnection == null ? string.Empty : agentConnection.Host),
Port = (agentConnection == null ? 0 : agentConnection.Port)
}).ToList();
return PartialView("_EngineConnection", connectionViewModels);
}
I have tried returning a JSON object, but that does not seem to do the trick. Is there a way to refresh just the grid, instead of the entire page, and still keep the grid inside the partial view?
Any suggestion will help!
Thanks
I would suggest you following way to bind the grid.
#(Html.Kendo().Grid<EntityStandardGridModel>()
.Name("KendoEntityStandardGrid")
.Columns(columns =>
{
//columns
})
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Sortable(sortable => sortable.AllowUnsort(false))
.Scrollable(scrollable => scrollable.Virtual(true))
.Resizable(resizable => resizable.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Model(model => model.Id(p => p.SearchId))
.Read(read => read.Action("GetStandardGriddata", "Search", new { SearchId = Model.SearchId }))
)
)

0x800a138f - JavaScript runtime error: The value of the property ''is null or undefined, not a Function object

1> I have kendo grid, and one of the column has a button. I have assigned javascript function to the onclick event of the button. The javascript makes ajax call. But when I click on the button I get error
0x800a138f - JavaScript runtime error: The value of the property 'DoSomething' is null or undefined, not a Function object
I tried setting onclick to "javascript:DoSomething();" with no luck
2> I would also like to pass "BatchKey" value to the function if possible
<div>
#(Html.Kendo().Grid< BatchDetail>()
.Name("grid")
.Columns(col =>
{
col.Bound(p => p.BatchKey);
col.Bound(p => p.OriginalCost);
col.Bound(p => p.Status);
col.Bound(p => p.LastFileName);
col.Bound(p => p.FileID).ClientTemplate(
"# if (Status == \"Error\") { #" +
"<button id=\"btnResolve\" class=\"resolve-button\" onclick=\"DoSomething();\">Resolve</button>" +
"#}#"
).Title("Action");
})
.AutoBind(true)
.Pageable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read
.Action("GetData", "Detail", new { ID = Model.ID })))
)
</div>
function DoSomething()
{
$.ajax({
url: "www.msn.com",
success: function (result)
{
$("#div1").html(result);
}
})
}
The button ID needs to be unique, so you can't use it like that. You can pass BatchKey like this:
col.Bound(p => p.FileID).ClientTemplate(
"# if (Status == \"Error\") { #" +
"<button class=\"resolve-button\" onclick=\"DoSomething(this, '#= BatchKey #');\">Resolve</button>" +
"#}#"
).Title("Action");
function DoSomething(button, batchKey)
{
$.ajax({
url: "www.msn.com",
success: function (result)
{
$("#div1").html(result);
}
})
}
I've tested this on my own grid and it works fine. If it still doesn't work there is an issue with code outside of what you've posted.

client template button event not firing

I'm trying to display a pop up window when a user clicks on a button but I cant seem to get this to work. I can fire the event when using a custom command but I need a textbox and button next to each other in the same column.
Any ideas why this isn't working?
#(Html.Kendo().Grid(Model)
.Name("gridPopup")
.Columns(columns =>
{
columns.Bound(p => p.ProductName).Width(120);
columns.Template(#<text></text>).Title("").Width(110).ClientTemplate(
Html.Kendo().TextBox()
.Name("search_textfield")
.Value("").ToClientTemplate().ToString()
+ " " +
Html.Kendo().Button()
.Name("search_button")
.HtmlAttributes(new { type = "button", #class = "k-primary" })
.Events(e =>
e.Click("SearchButton")
)
.Content("...").ToClientTemplate().ToString()
);
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:320px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(true);
model.Field(p => p.CategoryID).DefaultValue(1);
})
.Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
.Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
.Create(create => create.Action("ForeignKeyColumn_Create", "Home"))
.Destroy(destroy => destroy.Action("ForeignKeyColumn_Destroy", "Home"))
)
)
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function SearchButton(e)
{
alert("Search Button Clicked");
}
</script>
Weird! .Events(e => e.Click("SearchButton")) is not generating the onclick attribute if used inside a ClientTemplate()
Try this, it will work for you, but i will wait for someone to explain it :)
.HtmlAttributes(new { type = "button", #class = "k-primary", onclick = "SearchButton()" })
Edit:
The explanation that I found is here: How do I use a Kendo UI widget inside a Grid client column template?. It says script tags are not automatically evaluated inside a Grid client column template, so any included widgets will not be initialized.
Therefore initializing the nested controls in .Events(e => e.DataBound("onDatabound"))
function onDatabound()
{
jQuery("#gridPopup tbody [class='k-primary']").each(function () {
$(this).kendoButton({ "click": SearchButton });
})
}

Use Javascript function into Kendo Grid Template

I want to use Javascript Function in Kendo Grid Create.
For that I have defined the Javascript Function as,
<script>
function GetCompanyID()
{
return $("#Company").val();
}
</script>
And I want to use it in Create template of Kendo Grid as,
#(Html.Kendo().Grid<Invoice.Models.ViewModels.DossierViewModel>()
.Name("Dossier")
.Columns(columns =>
{
columns.Bound(p => p.CustomerName).Title("Customer").Width(150);
columns.Bound(p => p.InvoiceNumber).Title("INV no.").Width(100);//.Width(20);
columns.Bound(p => p.InvoiceAmountLC).Title("INV Amount LC").Width(150);
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Dossier"))
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("New_Dossier")) //Having Different Template for New Dossier
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model => { model.Id(p => p.DossierID); })
.Read(read => read.Action("Dossier_Read", "Dossier"))
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
.Filter(filters =>
{
// Show products whose ProductName property contains "C"
filters.Add(dossier => dossier.Status).Contains("");
})
)
)
In that I want to use that Javascript functio as I am currently using in Above code as,
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
But this is not the Way it should be used. Please Help me on this. How can I use that Javascript function into this, ASAP.
You need to use the Data() method of the grid data source to send this data. Something like:
.Create(create => create.Action("Dossier_Create", "Dossier").Data("GetCompanyID")
function GetCompanyID()
{
return {
CompanyID: $("#Company").val();
};
}
Check the grid FAQ for more info and an example.

Categories

Resources