How to get ckeditor textarea value using jquery? - javascript

I am using ckeditor on textarea but i could not get data from it.
Code :
<textarea name="DSC" class="materialize-textarea"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
Jquery :
var title = $('input[name=TITLE]').val();
var desc = $('textarea[name=DSC]').text();
var formdata = 'TITLE='+title+'&DSC='+desc;

No need for jQuery CKEditor has its own method to get data from converted textarea:
var desc = CKEDITOR.instances['DSC'].getData();
OR:
var desc = CKEDITOR.instances.DSC.getData();

Use id attibute in textarea and use that id in CKeditor instead of textarea's name check bellow
<textarea name="textareaname" id="textarea-id"></textarea>
CKEDITOR.replace( 'textarea-id');//use id not name//
var ckValue = CKEDITOR.instances["textarea-id"].getData(); or
var ckValue = CKEDITOR.instances.textarea-id.getData();

alert(CKEDITOR.instances.DSC.getData());

Past Text area id below.
CKEDITOR.instances['Text_Area_Id_Here'].getData();
For example, i have text area
<textarea class="form-control" id="Description" name="description" width="100%" height="150" ckeditor="true" maxlength="20000" ismandatory="false">
</textarea>
I got value of text area like this
var description = CKEDITOR.instances['Description'].getData();

Using the jQuery_Adapter you may write:
$(function () {
$('textarea[name="DSC"]').ckeditor();
$('#btn').on('click', function(e) {
console.log('ckeditor content: ' + $('textarea[name="DSC"]').val());
})
});
Include files:
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.5.9/adapters/jquery.js"></script>
HTML:
<textarea name="DSC" class="materialize-textarea"></textarea>
<button id="btn">Get text</button>

<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<button type="button" id="getDataBtn">Get Data</button>
</form>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
$(document).ready(function(){
$("#getDataBtn").click(function(){
var editorData= CKEDITOR.instances['editor1'].getData();
alert(" your data is :"+editorData);
})
});
</script>

//getting data form ckeditor in textarea.
var NodeDataSessionTextarea = {};
jQuery('.class-textarea').each(function(index, el) {
var editor_id = jQuery(this).attr('id');
var elevalue = jQuery(this).val();
// Getting ckeditor instance.
var editor = CKEDITOR.instances[editor_id];
if (editor) {
editor.on('key', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on('afterCommandExec', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on( 'blur', function() {
//store data in session
var nodedataencodetextarea = JSON.stringify(NodeDataSessionTextarea);
sessionStorage.setItem("NodeDataSessionTextarea", nodedataencodetextarea);
});
}
});
//put data in ckeditor.
var editor = CKEDITOR.instances[id];
if (editor) {
editor.setData(getTemplateData);
}

For an update of Bogdan Kuštan's answer using CKEditor 5 (tested in may 2022):
editor.getData() is the new way of getting the Data from the editor.
Here is one common example of using it: filling an hidden field on submitting the form.
import ClassicEditor from '.../src/ckeditor.js';
ClassicEditor
.create('#editor-container')
.then(editor => {
persistForm(editor);
};
function persistForm(editor)
{
document.querySelector('form').addEventListener('submit', (e) => {
document.querySelector('.hidden-input').value = editor.getData();
});
}
This post is also a reminder for myself later.

You should use getData() method to get data from CKEDITOR.
<textarea name="DSC" class="materialize-textarea" id="DSC"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
//reference the id DSC
var desc = CKEDITOR.instances['DSC'].getData();

Related

How to alert a selected text inside kendo editor

How to alert a selected text inside kendo editor?
I tried below code
<textarea id="editor"></textarea>
<script>
$("#editor").kendoEditor();
var editor = $("#editor").data("kendoEditor");
var html = editor.getSelection();
</script>
But it gives me error:
Cannot use 'in' operator to search for 'getSelection' in undefined`
Then my textarea is
<textarea id="editor" kendo-editor k-ng-model="html"></textarea>
<script>
var textarea = $("#editor");
textarea.kendoEditor({ value: "Hello, how are you doing !" });
var editor = textarea.data("kendoEditor");
$('#buttonB').click(function () {
alert(textarea);
alert(editor.getSelection());
});
</script>
Using what I saw in Kendo documentation (https://demos.telerik.com/kendo-ui/editor/events), adding a select property assigned to a function triggered by the select event:
<script>
var textarea = $("#editor");
textarea.kendoEditor({
value: "Hello, how are you doing !",
select: onSelect
});
var editor = textarea.data("kendoEditor");
function onSelect() {
alert(editor.getSelection());
}
$('#buttonB').click(function () {
alert(textarea);
alert(editor.getSelection());
});
</script>

HTML5 Javascript . how to Save Textarea input then loading it via buttons

I have a project I'm working on where there's a "Save" button that saves the user's data to localStorage and there's a "Load" button that loads a user's saved data from localStorage. However, it's not working. Can someone please help me fix this problem?
HTML:
<textarea rows="10" cols="50" id="text"></textarea>
<br/><button id="save">Save</button>
<button id="load">Load</button>
JavaScript:
function doSave(){
var txt = text.value;
localStorage.storedText= txt;
}
function doLoad(){
text.value = localStorage.storedText;
}
window.onload = function(){
saveButton = document.getElementById("save");
saveButton.onclick = doSave();
loadButton = document.getElementById("load");
loadButton.onclick = doLoad();
textarea = document.getElementById("text");
};
You're using localStorage incorrectly:
function doSave(){
//Set the item in doSave()
//localStorage.setItem("text", text.value);
}
function doLoad(){
//Get the item in doLoad()
//text.value = localStorage.getItem("text");
}
Also, read Quentin's answer: Don't call doSave() and doLoad() when setting the onclick event:
//When the window loads...
window.onload = function(){
saveButton = document.getElementById("save");
saveButton.onclick = doSave;
loadButton = document.getElementById("load");
loadButton.onclick = doLoad;
textarea = document.getElementById("text");
};
Here's the "fiddle": http://jsfiddle.net/NobleMushtak/JNKaU/
You have to assign functions to onclick properties. You are calling doSave and doLoad and assigning their return values. Since those functions do not have return statements, they return undefined.
Remove the (). Don't call them immediately.

After submiting the text disappears jQuery

When I write some text in the input field. And want it displayed below the input field, when pressing the submit button it disappears. I don't know why.
Live Demo
HTML:
<textarea id ="comments" cols="30" rows="3"></textarea>
<input type="submit" value="Submit" id="submit"/>
<div id="divComments"></div>
Jquery:
function addComment(name1) {
var container = $('divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
You missed the # for id selector, change
var container = $('divComments');
to
var container = $('#divComments');
See the fixed demo.
The selector for the divComments div is missing the # for the id selector.
function addComment(name1) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
Working fiddle.
As well as fixing the following line to add a hash
var container = $('#divComments');
you will also want to change the submit function:
$('#submit').click(function (e) {
e.preventDefault();
addComment($('#comments').val());
$('#comments').val("");
});
This will stop the form actually been submitted (and reloading the page) - which is probably the reason for your text disappearing. If you don't have a form surrounding your inputs then you don't need to bother with the second part of this answer.

Display description in Username and Password field

I'm trying to create a similar login as in https://login.microsoftonline.com/. I want to display a description "someone#example.com" and "Password" in the fields.
I've tried to use the txReplaceFormPassword.js (http://snipplr.com/view/29555/) script to dynamically replace the fields but it is returning html text instead of the actual field.
<head>
<script src="#Url.Content("~/Scripts/txReplaceFormPassword.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.pwdfield').txReplaceFormPassword({
show_text: 'Password'
});
});
</script>
</head>
<div class="pwdfield">
#Html.PasswordFor(model => model.Password, new {#class = "k-textbox", style = "width:300px"})
#Html.ValidationMessageFor(model => model.Password)
</div>
I'm getting the following output in the browser:
Please let me know how can I get a description inside Password/Username field similar to the two links above.
Thanks.
I think this is what you want:
<input type="text" placeholder="someone#example.com" /><br />
<input type="password" placeholder="Password" />
As far as I know, you don't need to use js or jQuery for that. Just set the placeholder="" to the text you want to show in the fields.
Take a look on this link.
EDIT
Then use the following jQuery (tested on ie 7):
(function($){
var placeholderIsSupported = ('placeholder' in document.createElement('input'));
$.fn.emulatePlaceholder = function(){
if(!placeholderIsSupported){
this.each(function(index, element){
var handle = $(element);
var placeholder = handle.attr('placeholder');
if(handle.val() == ''){
handle.val(placeholder);
}
handle.blur(function(e){
var handle = $(this);
if(handle.val() == ''){
handle.val(placeholder);
}
});
handle.focus(function(e){
var handle = $(this);
if(handle.val() == placeholder){
handle.val('');
}
});
});
}
};
})(jQuery);
USAGE:
$('input').emulatePlaceholder();
jsFiddle example

CKEDITOR: get data from multiple instance names in Javascript

Because I have multiple textareas in HTML code, I pass the id value through Javascript to retrieve the data in each textareas. However, in the JS function, the "CKEDITOR.instances.id" doesn't represent as expected such as CKEDITOR.instances.editor_1, CKEDITOR.instances.editor_2, or CKEDITOR.instances.editor_4, therefore, I don't have any data retrieved. Anyone knows how to fix this please let me. Heaps of thanks.
HTML code:
<textarea name="edit_1"></textarea>
<input type="button" value="submit" onClick="getValue('edit_1')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_2')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_3')" />
JS code:
var getValue = function(id) {
var content = CKEDITOR.instances.id.getData();
alert(content);
};
Try adding [] between id
var getValue = function(id) {
var content = CKEDITOR.instances[id].getData();
alert(content);
};
i had to do something like this as i was binding events to actions with multiple instances.
and trying to get the data but it would always return null for any one but the last... using the event (e.editor) worked though.
var editors = CKEDITOR.instances;
for (var x in editors) {
if (editors[x]) {
var thisName = editors[x].name;
if (editors[thisName]) {
editors[thisName].on('focus', function (e) {
socket.emit('ckeditor_field_type_edit', user, e.editor.name);
});
editors[thisName].on('key', function (e) {
var data = e.editor.getData();
socket.emit('ckeditor_field_type_typing', user, e.editor.name, data);
});
editors[thisName].on('blur', function (e) {
var data = e.editor.getData();
setTimeout(function () {
socket.emit('ckeditor_field_type_edit_finish', user, e.editor.name, data);
}, 1000);
});
}
}
}

Categories