0

Problem - On my html page there's one textarea. Code is -

<div id ="textFields" class="form-group">
        <p align="center">
        <br>
        <textarea placeholder="Enter note, max limit 200 words" class="form-control" rows="5" id="note" style="width: 80%;overflow:auto;"></textarea>
            <script>CKEDITOR.replace( 'note' );</script>
         </p>
</div>

Now I want to create multiple textareas, for which I'm using an Add button and the jQuery code -

$(document).ready(function(){
$("#addNew").click(function () {
    var inputField = jQuery('<p align="center"><br><textarea placeholder="Enter note, max limit 200 words" class="form-control" rows="5" id="note" style="width: 80%;overflow:auto;"></textarea><script>CKEDITOR.replace( 'note' );</script></p>');
    jQuery('#textFields').append(inputField);
}); });

When I click the #addNew button, the textarea is created but the CKEditor script is not loaded. This results in a plain textarea without CKEditor's functionalities.

How do I create a new textarea with CKEditor functionalities? Is there another way? Is my approach wrong?

1
  • Your textarea's ID has to be unique. You can append an incremented counter to it. Make sure you use the same in the <textarea> tag and the call to CKEDITOR.replace. Also don't add the <script> tag when creating the jQuery object, just call the function after appending the textarea element. Commented May 3, 2017 at 16:13

1 Answer 1

1

First, an id is an unique identifier in html and you shouldn't use it more than once.

Second, you can't add script tags, which get executed, that way. I would suggest to restructure your code like this

<div id ="textFields" class="form-group">
    <p align="center">
        <br>
        <textarea id="note0" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width: 80%;overflow:auto;"></textarea>
    </p>
</div>

with the following javascript

$(document).ready(function(){
    var note_id = 0;
    CKEDITOR.replace('note0');
    $("#addNew").click(function () {
        note_id++;
        var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width: 80%;overflow:auto;"></textarea></p>');
        $('#textFields').append(inputField);
        CKEDITOR.replace('note' + note_id);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, man. I forgot about the unique textarea id. The CKEditor method you showed helped a lot. Guess I have to learn javascript properly. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.