Search code examples
javascripttextckeditor

Getting non-html text from CKeditor


In my application, in insert news section, i use a sub string of news content for news Summary. for getting news content text from users,i use CKEditor and for news summary i use substring method to get a certain length of news content.but when i'm working with CKEditor i get text with html tags and not plain text and when i use substring method, my news summary become messed! how do i get raw text from this control? i read this but i can't use getText() method


Solution

  • do it like this

    //getSnapshot() retrieves the "raw" HTML, without tabs, linebreaks etc
    var html=CKEDITOR.instances.YOUR_TEXTAREA_ID.getSnapshot();
    var dom=document.createElement("DIV");
    dom.innerHTML=html;
    var plain_text=(dom.textContent || dom.innerText);
    
    alert(plain_text);
    

    viola, grab the portion of plain_text you want.

    UPDATE / EXAMPLE

    add this javascript

    <script type="text/javascript">
    function createTextSnippet() {
        //example as before, replace YOUR_TEXTAREA_ID
        var html=CKEDITOR.instances.YOUR_TEXTAREA_ID.getSnapshot();
        var dom=document.createElement("DIV");
        dom.innerHTML=html;
        var plain_text=(dom.textContent || dom.innerText);
    
        //create and set a 128 char snippet to the hidden form field
        var snippet=plain_text.substr(0,127);
        document.getElementById("hidden_snippet").value=snippet;
    
        //return true, ok to submit the form
        return true;
    }
    </script>
    

    in your HTML, add createTextSnippet as onsubmit-handler to the form, eg

    <form action="xxx" method="xxx" onsubmit="createTextSnippet();" />
    

    inside the form, between <form> and </form> insert

    <input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
    

    When the form is submitted, you can serverside access hidden_snippet along with the rest of the fields in the form.