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');
});