Get formatted HTML from CKEditor - javascript

I'm using CKEditor in my web app, and I'm at a loss as to how to get the contents of the editor with HTML formatting.
var objEditor = CKEDITOR.instances["sectionTextArea"];
var q = objEditor.getData();
This will get me the text entered in CKEditor, without any markup.
However,
var q = objEditor.getHTML();
will return a null value. What am I doing wrong?

getHTML isn't a method of a CKEditor object, so instead of null you should have a javascript error.
The method defined by the api is getData() if that doesn't work then you have some other problem in your code, try to use an alert to verify the contents at that moment.

just to know that the right method for this is getData() didn't help me. I did not know how to use it on the CKEditor object. and CKEDITOR.getData() doesn't work.
this is how getData() is used on the CKEDITOR object:
CKEDITOR.instances.my_editor.getData()
...where my_editor is the id of your textarea used for CKEditor.
The opposite of it is setData():
CKEDITOR.instances.my_editor.setData("<p>My Text</p>");

To get htmlData from editor you should use the code snippet bellow:
var htmldata = CKEDITOR.instances.Editor.document.getBody().getHtml();
If this solution won't work, check if you have BBCode plugins uninstalled.

Please update ckeditor config.js with the following line
config.fullPage = true;
This will return the full html when you request getData();

This worked for me:
CKEDITOR.instances["id"].getData()

I am using the preview plugin to get the full HTML content, hope it helps.
CKEDITOR.getFullHTMLContent = function(editor){
var cnt = "";
editor.once('contentPreview', function(e){
cnt = e.data.dataValue;
return false;
});
editor.execCommand('preview');
return cnt;
}

in ckeditor 5, you can get the html data with editor.getData()
here is an example:
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log(editor.getData());
} )
.catch( error => {
console.error( error );
} );

For Java Users...
After pressing the submit button, the request goes by HTTP Post method. This Post request also contains the formatted html in the parameter named using the name attribute of the textarea.
So, if your textarea is something like...
<form method="post" action="createPDF.do"> <textarea name="editor1" id="editor1"/>
<input type="submit"/> </form>
Then, after pressing the submit button, you can get the formatted html in your servlet/controller by :
String htmlContent = request.getParameter("editor1");
You can also pass this variable containing the formatted html ('htmlContent') to ITEXT (or some other pdf converters) to create the pdf...

I realize this is old, but I had trouble finding an answer that made sense and returned the actual HTML, including images. If your ckeditor instance is attached to a textarea, you can simple get the value of the textarea to get the HTML.
For instance, if you're using jQuery:
$('#my_editor').val()
No need to go digging through the API.

If you have two CKEditor, you can use code bellow:
HTML
<textarea name="editor1"></textarea>
<textarea name="editor2"></textarea>
JS
CKEDITOR.replace( 'editor1' );
CKEDITOR.replace( 'editor2' );
var objEditor1 = CKEDITOR.instances["editor1"];
alert(objEditor1.getData()); // get html data
var objEditor2 = CKEDITOR.instances["editor2"];
alert(objEditor2.getData()); // get html data
Online Demo (jsfiddle)

I used the insert media feature in editor and .getData() did not return the required HTML to show the video thumbnail icon. The following worked for me to get the final HTML:
$(".ck-content").html()

Try this:
CKEDITOR.instances.YOUREDITOR.element.getHtml();
with CKEDITOR.instances.YOUREDITOR.element you select a DOM element and if you use
CKEDITOR.instances.YOUREDITOR.element.getHtml();
you can get all html from editor element.

Related

How do you insert HTML into a QuillJS?

Is it possible to insert raw HTML into a Quill? I've been searching the documentation but couldn't find anything.
If it's not possible, can I at least convert HTML into a Quill Delta?
The reason I need this is because I am grabbing the raw HTML of the text taken from Quill, so I can view it later in HTML style. Have I been doing everything wrong, and need to keep a Delta version of it as well?
On version 1.3.6,
You can use Quill.setContents(value) method.
And insert your new HTML like this:
const value = `<h1>New content here</h1>`
const delta = quill.clipboard.convert(value)
quill.setContents(delta, 'silent')
Quill documentation: https://quilljs.com/docs/api/#setcontents
I have found a way, looking extremely closely at the documentation. Method quill.clipboard.dangerouslyPasteHTML('raw html'); does the trick. https://quilljs.com/docs/modules/clipboard/#dangerouslypastehtml
Another way to insert HTML into Quill is by using vanilla JavaScript.
You can set your html to a variable, such as htmlToInsert.
Then target the contenteditable div created by Quill, by getting it by its class, ql-editor.
Finally, set the innerHTML of that div to the HTML you want to insert.
For example:
var htmlToInsert = "<p>here is some <strong>awesome</strong> text</p>"
var editor = document.getElementsByClassName('ql-editor')
editor[0].innerHTML = htmlToInsert
There is better way to do this:
const htmlMurkup = '<p>Good</p>'
let quill = new Quill()
quill.container.firstChild.innerHTML = htmlMurkup
I believe the most straight forward way is this:
quill.root.innerHTML = '<p>HTML Goes Here</p>'
You can also obtain the HTML from this property as well.
If you aren't getting the desired output. It could be because your html content is encoded.
Use this to convert it.
let realHTML = $('<textarea />').html("<p><strong>Hello</strong></p><p><br></p>").text();
console.log(realHTML);
This code will output
<p><strong>Hello</strong></p>
After this you can use this command to set the html content in quill editor
quill.root.innerHTML = realHTML;
or even this:
let initialContent = quill.clipboard.convert(realHTML);
quill.setContents(initialContent, 'silent');
Its proper your html is in the real html format before setting the value on quill. Else the html tags would be displayed verbally.
Just to add to #user1993629's answer, using quill.clipboard.dangerouslyPasteHtml(0, "raw html") will place the cursor at the end of the pasted content

How to get source code of html page

This is a link for an example of Edit source Code:
http://neokoenig.github.io/jQuery-gridmanager/demo/tinymce.html
the button which value is </>.
He get the code HTML even if he changes the content of the grid.
How to get the source code HTML using JavaScript or jQuery?
Thanks.
Using JavaScript
document.documentElement.outerHTML
More info
or
document.documentElement.innerHTML
More info
you can use the html method with jquery, i.e for get the whole page html like this:
$( document ).ready(function() {
console.log($("html").html());
})
I'm not sure what you want to do exactly but if you want to get raw source code from jQuery you can use the following:
var html = $('element').html();
And with pure javascript from an id
var html = document.getElementById('id').innerHTML;
or from classname
var html = document.getElementsByClassName('class').innerHTML;
And to get the content of your example (which is an editor called tinymce) you can use the command tinymce.activeEditor.getContent(); or tinyMCE.get('myTextarea').getContent()
EDIT:
If you want to listen for changes with jQuery and display to html dynamically you'd want to do something like this:
$('yourTextArea').keyup(function() {
var html = $(this).val();
$('yourElementToDisplayTheHTML').html(html);
});
I've built a simple API, just use this:
<script src="https://cdn.jsdelivr.net/gh/Parking-Master/viewsource#latest/vs.js"></script>
In your JavaScript:
getSource('https://example.com/');
in http response header, you can find "content-type" header. that header indicates how contents of page should be rendered. so, if you want to render page as plain text("source code", as you mentioned), just change that header like this -> "content-type : text/plain; charset=UTF-8"
if you can use ajax in jquery or javascript
use like this
$("button").click(function(){
$.ajax({url: "page_you_want.html", success: function(result){
alert(result);
}});
});

How to read text from textfield using jQuery to the variable?

So, I got the page on my local server, and this page contains textarea and button. I am Trying to write onclick function to button, which would read whatever I typed in text area, and make record to database. Just like when I finish typing my question here, and press Ask Question. The problem is that I can't properly read text in text area, it basically sees only what was in there at the moment of loading a page, and just rewrite it. How should I get text, that I typed right before clicking the button? I just want to know how can I copy that text to some var, which I can PUT to database.
$.getJSON('/link/' + tenderId, function (data) {
var description = '';
description += '<textarea id="description" class="form-control" rows="3">' + data.description + '</textarea>';
$('#description').html(description);
});
Use this code inside your click event
var textareaValue = $('textarea#textareaId').val();
html
<textarea id="textareaId"></textarea>
SO answer: https://stackoverflow.com/a/144836/2772017
You need to use val() (I am guessing you are using text()) to get the text of a Text Area:
$('input#mybutton').click(function() {
var text = $('textarea#mytextarea').val();
});
Of course this is just guesswork as you did not supply any code! :)
Update:
The code you added is also incorrect as it adds a duplicate id of description inside a div with an id of description! ID's need to be unique on a page.
Assuming you want a new id here is a cleaner version of your code:
$.getJSON('/link/' + tenderId, function (data) {
var $textArea = $("<textarea>", {class: "form-control", id: "descriptionText", rows: "3"}).val(data.description);
$('#description').empty().append(description);
});
I can't figure out you method logic; it seems you are pulling some json data then appending it to a textarea while in issue description you said that you are trying to save the textarea content so you have to be sending it throug a POST request.
Also does the <textarea id="description"...> element is there in your page or you will be creating it at each button click?
If such is you case, you can try with the following snippet:
$.getJSON('/link/' + tenderId, function (data) {
var $description = $("<textarea>");
$description.attr({
id:'description',
class:'form-control',
rows:'3'})
.html(data.description);
//you will have then to append this jQuery element, e.g: $("#wrapper").append($description)
});
$('button').click(function(){
var myString = $('#description').val();
})
Then use myString whereever you like.

How change the CKEditor text using jQuery?

I have a textarea with CKEditor (bbCode Plugin).
<textarea id="editor1" name="conteudo" class="form-control" rows="3" required></textarea>
This is my CKEditor instance:
$( document ).ready( function() {
$( 'textarea#editor1' ).ckeditor();
} );
I'm making a JSON request that takes a value and I want this value to be modified in this textarea, I tried with jQuery but not worked !
Below is my attempt:
video_id = "lLi1Lx2xTKI";
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
description = data.data.description;
// Attempt here
$("#editor1").html(description);
});
UPDATE
I tried using '.val()' and not worked!
You can't simply add text to the CKEDITOR via jQuery, instead go with api given by CKEDITOR
CKEDITOR.instances.editor1.setData(data.data.description);
Here your code looks like
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
CKEDITOR.instances.editor1.setData(data.data.description);
});
Fiddle
Instead of writing the description directly into the text area, try the CKEditor setData method. You can find a description of it here:
http://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-popup
also be sure that your description variable does have a value, I'd use a temporary alert(description); for this but you may be able to do it with a javascript debugger also.

Getting element by tag name after getting a page using jQuery $.get

I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.

Categories