how to set text in ckeditor - ckeditor

How do I set text in CKEditor? CKEditor also needs to integrate with ckfinder.
I tried doing
// I need to set ckeditor text with a value in code behind. To get that value from code bhind, I am using a div which would be set in code behind. This is not hidden currently but I would do that eventually. I need to set this value to my ckeditor.
<textarea id="editor1" name="editor1"></textarea>
<script type="text/javascript">
window.onload = function () {
var edt = CKEDITOR.replace('editor1', { toolbar: 'Basic' });
CKFinder.setupCKEditor(edt, '/ckfinder/');
var t = <%=editortext.InnerText %>;
CKEDITOR.instances.editor1.setData(t);
}
If I put some static text for t, var t = "Some Text";
and then set
CKEDITOR.instances.editor1.setData(t); it works fine.
If I use,
var t = <%=editortext.InnerText %>;
CKEDITOR.instances.editor1.setData(t);
ckeditor is no longer displayed. Only text area is displayed. How to set text in ckeditor ? Please help

This syntax may be useful here:
CKEDITOR.instances['editor1'].setData(t); // where editor1 is id
OR try this
edt.setData(t);

<script>
function SetContents(value ) {
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value ;
oEditor.setData(t);
}
</script>
<script type="text/javascript">
var ckEditor = CKEDITOR.replace('<%=editor1.ClientID %>', {
// extraPlugins: 'bbcode',
// fullPage : true,
extraPlugins: 'docprops',
removeDialogTabs: 'image:advanced',
filebrowserImageUploadUrl: 'Upload.ashx',
resize_enabled: false,
toolbar: [
['Source', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
['FontSize', 'TextColor', 'BGColor'],
['Image']
]
});
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value;
oEditor.setData(t);
function pageLoad() { // this is because after postback jquery not working
var instance = CKEDITOR.instances['<%=editor1.ClientID %>'];
if (instance) {
CKEDITOR.remove(ckEditor);
}
CKEDITOR.replace('<%=editor1.ClientID %>', {
// extraPlugins: 'bbcode',
// fullPage : true,
extraPlugins: 'docprops',
removeDialogTabs: 'image:advanced',
filebrowserImageUploadUrl: 'Upload.ashx',
resize_enabled: false,
toolbar: [
['Source', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
['FontSize', 'TextColor', 'BGColor'],
['Image']
]
});
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value;
oEditor.setData(t);
}
</script>

Check in your browser's console for errors first. Also observe what is rendered from your backend code into this template. Most likely what you're missing are quotation marks "" and/or your rendered string contains unescaped apostrophes/quot. marks.
Console is everything.

this post is quote old but I hope I am not too late for others to see this:
You forgot to enclose the server side code with quotes:
var t = "<%=editortext.InnerText %>";
the page will be rendered like this:
var t = "your text here";
instead of
var t = your text here;
using your code will definitely break javascript's parser

You just put double quotes
for example :-
var mata = CKEDITOR.replace('meta_des');
var editor = CKEDITOR.replace('des1');
mata.setData("meta_des; ?>");
editor.setData("description1 ;?>");
here my meta_des is ckeditor and i want past my value in that ckeditor i will just put double quotes on my php tag and simply it will print my value that comes in database it will print.

Related

CKEditor5 insert non-editable text in the editor

I am trying to insert small pieces of text in the CKEditor5, like
{{ variable name }}
These variables shall not be edited by user. I tried to insert
content = '<span contenteditable="false">' + content + '</span>';
Using the following code, content is the non-editable string
content = '<span contenteditable="false">' + content + '</span>';
const viewFragment = this.editor.data.processor.toView( content );
const modelFragment = this.editor.data.toModel( viewFragment );
this.editor.model.insertContent( modelFragment );
It does not work. The wrapping part is always removed by CKEditor. What should I do to achieve this?
you should configure editor to allow for other tags
and you need html Editing plugin (sorry I forgot the real name of it)
public config = {
placeholder: 'content here',
htmlSupport: {
allow: [
{
name: /.*/,
attributes: true,
classes: true,
styles: true
}
]
}
}

Kendo UI Editor, show HTML in Editor with encode html entities

I would like to see HTML in the Kendo UI Editor like
<h1>Hello World</h1>
How can i do these?
My sample show on: https://dojo.telerik.com/ezOPAz/3
$("#editor").kendoEditor({
value: "<h1>Hello World</h1>",
encoded: false,
tools: [
"viewHtml"
],
deserialization: {
custom: function(html) {
var encodedStr = html.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
return encodedStr;
}
}
});

post kendo editor value as html rich text

I have noticed a problem with Kendo ui editot when posting (via ajax) editor.value() rich html text to the server.
when posting a few lines with html design -> in the server I get only the first line until the first '&nbsp'.
$("#emailTxtEditor").kendoEditor({
//encoded: false,
resizable: true
});
for instance I take This Sample and after designing some text the post missing lot's of the html content...
ps, in the server there is no model becuase i don't save this content.
How can resolve this issue ?
You can do something like this:
$("#emailTxtEditor").kendoEditor(
{
tools:
[
"bold",
"italic",
.....
],
messages: {
bold: "Bold",
italic: "Italic",
underline: "Underline",
....
},
encoded: false,
keyup: function () {
$("#YourTextbox").val(encodeURIComponent($("#emailTxtEditor").data("kendoEditor").value())),
$("#YourTextbox").focusin()
},
change: function () {
$("#YourTextbox").val(encodeURIComponent($("#emailTxtEditor").data("kendoEditor").value())),
$("#YourTextbox").focusin()
}
})
And in controller:
var emailContent = HttpUtility.UrlDecode(Email.EmailContent);//Email is model (for ex)

How to populate Kendo Upload with previously uploaded files

I'm using the Kendo UI File Upload for MVC and it works great. On my edit page, I want to show the files that were previously uploaded from the Create page. For visual consistency, I would like to re-use the upload widget on my edit page so the user can use the "remove" functionality, or add additional files if they choose. Does the upload widget support this?
Thanks!
So, I realize this is question pretty old, but I recently figured out how to do this reliably. While the other answer on here will certainly display the files, it doesn't really wire it up to any of the events (specifically the "remove" event). Also, rather than manually setting all of this up, I figured I'd much rather have Kendo do all of the real dirty work.
Note, this only applies if your file upload is not set to autosync. If you use the auto upload feature, you can find examples in the Kendo documentation here: http://docs.kendoui.com/api/web/upload#configuration-files
So anyway, let's assume we have a file input that we've made into a Kendo Upload:
<input id="files" name="files" type="file" multiple="multiple" />
$(document).ready(function () {
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
$upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
});
}
Then, we just need to get the information about the files to our jQuery. I like to jam it into JSON strings in hidden fields, but you can do it however you want.
Here's an example using the Mvc HtmlHelpers and Newtonsoft's JSON.NET (I don't use Razor, but you should get the general idea):
if (Model.Attachments.Count > 0)
{
var files = Model.Attachments.Select(x => new { name = x.FileName, extension = x.FileExtension, size = x.Size });
var filesJson = JsonConvert.SerializeObject(files);
Html.Render(Html.Hidden("existing-files", filesJson));
}
Note, the format there is incredibly important. We're tying to match the structure of the JavaScript object that Kendo is expecting:
{
relatedInput : sourceInput,
fileNames: [{ // <-- this is the collection we just built above
name: "example.txt",
extenstion: ".txt",
size: 1234
}]
}
So, then all that's left to do is put it all together. Basically, we're going to recreate the onSelect function from Kendo's internal syncUploadModule:
$(document).ready(function () {
// setup the kendo upload
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
var upload = $upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
}).getKendoUpload();
// initialize the files
if (upload) {
var filesJson = $("[name$='existing-files']").val();
if (filesJson) {
var files = JSON.parse(filesJson);
var name = $.map(files, function (item) {
return item.name;
}).join(", ");
var sourceInput = upload._module.element.find("input[type='file']").last();
upload._addInput(sourceInput.clone().val(""));
var file = upload._enqueueFile(name, {
relatedInput : sourceInput,
fileNames : files
});
upload._fileAction(file, "remove");
}
}
});
And that's pretty much it!
I came up with a way to do this.
Basically, you need HTML that mimics what the Upload control generates, and you use a bit of JavaScript to hook each item up. I initially render the HTML as hidden, then after you initialize the Kendo Upload control, you append the HTML list to the parent container that Kendo creates.
This is my MVC view:
#if (Model.Attachments != null && Model.Attachments.Count > 0)
{
<ul id="existing-files" class="k-upload-files k-reset" style="display: none;">
#foreach (var file in Model.Attachments)
{
<li class="k-file" data-att-id="#file.Id">
<span class="k-icon k-success">uploaded</span>
<span class="k-filename" title="#file.Name">#file.Name</span>
<button type="button" class="k-button k-button-icontext k-upload-action">
<span class="k-icon k-delete"></span>
Remove
</button>
</li>
}
</ul>
}
and here is the JavaScript (note, it was generated from CoffeeScript):
var $fileList, $files, item, _fn, _i, _len;
$fileList = $("#existing-files");
if ($fileList.length > 0) {
$(".k-upload").append($fileList);
$files = $(".k-file");
_fn = function(item) {
var $item, fileId, filenames;
$item = $(item);
fileId = $item.data("att-id");
filenames = [
{
name: fileId
}
];
return $item.data("fileNames", filenames);
};
for (_i = 0, _len = $files.length; _i < _len; _i++) {
item = $files[_i];
_fn(item);
}
$fileList.show();
}
You can find the full write up on my blog where I go into depth on the topic. I hope this helps you!
Some additional searches gave me the answer I wasn't looking for - According to this and this, Telerik does not support pre-populating an upload widget with previously uploaded documents.
It has been added in the options since this question has been asked.
Check out http://docs.telerik.com/kendo-ui/api/web/upload#configuration-files
It only works in async mode.
Try this...
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveFile", "Home")
.Remove("RemoveFile", "Home")
.AutoUpload(true))
.Files(files =>
{
foreach (var file in Model.FundRequest.Files)
{
files.Add().Name(file.Name).Extension(Path.GetExtension(file.Name)).Size((long)file.SizeKb * 1024);
}
}))
My Model has a reference to my "FundRequest" object that has a List of "File" objects, so I just loop through each "File" and add.
Check this out!
<script>
var files = [
{ name: "file1.doc", size: 525, extension: ".doc" },
{ name: "file2.jpg", size: 600, extension: ".jpg" },
{ name: "file3.xls", size: 720, extension: ".xls" },
];
$("#upload").kendoUpload({
async: {
saveUrl: "Home/Save",
removeUrl: "Home/Remove",
autoUpload: true
},
files: files
});
</script>
<input type="file" name="files" id="upload" />
Check this out, this is it.
Below code is copied and adapted from kendo-ui documentation:
<div id="example">
<div>
<div class="demo-section">
<input name="files" id="files" type="file" />
</div>
</div>
<script>
$(document).ready(function () {
if (sessionStorage.initialFiles === undefined) {
sessionStorage.initialFiles = "[]";
}
var initialFiles = JSON.parse(sessionStorage.initialFiles);
$("#files").kendoUpload({
showFileList: true,
multiple: true,
async: {
saveUrl: "save",
autoUpload: false,
batch: true
},
files: initialFiles,
success: onSuccess
});
function onSuccess(e) {
var currentInitialFiles = JSON.parse(sessionStorage.initialFiles);
for (var i = 0; i < e.files.length; i++) {
var current = {
name: e.files[i].name,
extension: e.files[i].extension,
size: e.files[i].size
}
if (e.operation == "upload") {
currentInitialFiles.push(current);
} else {
var indexOfFile = currentInitialFiles.indexOf(current);
currentInitialFiles.splice(indexOfFile, 1);
}
}
sessionStorage.initialFiles = JSON.stringify(currentInitialFiles);
}
});
</script>
</div>

Integrating CKEDITOR.replace and Perch to use two editors

In CKEDITOR's documentation there are suggestions to use the following in the config.js file:
CKEDITOR.editorConfig = function( config ) {
config.toolbar_Full = [
{ name: 'document', items : [ 'Source','-',
'Save','NewPage','DocProps','Preview',
'Print','-','Templates' ] }
];
config.toolbar = 'Full';
};
Though that actually does not work. It only works without the parens:
CKEDITOR.editorConfig = function( config ) {
config.toolbar_Full = [
[ 'Source','-','Save','NewPage','DocProps',
'Preview','Print','-','Templates' ]
];
config.toolbar = 'Full';
};
Now, Perch also has this little rig: CKEDITOR.replace that is meant to be used inline, but I would like to use it in the config.js file. How do I rewrite the call to CKEDITOR.replace so that it works inside config.js?
CKEDITOR.replace( 'editor1', {
toolbar : 'Full'
});
CKEDITOR.replace( 'editor2', {
toolbar : 'Basic'
});
As I replied in CKEditor forums, you must be using an old version of CKEditor, that toolbar syntax was introduced in CKEditor 3.6
Just load the CKEditor with your custom config:
CKEDITOR.replace( 'editor1', {
toolbar: [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ]
});
Or define your custom toolbar and load it:
CKEDITOR.replace( 'editor2', {
toolbar_Custom: [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ],
toolbar: 'Custom'
});

Resources