Ronnie Oosting
Ronnie Oosting

Reputation: 1252

Javascript inserttext with newline

I cannot get below code working:

<button type="button" class="btn btn-success btn-sm pull-right" style="margin-bottom:5px;margin-right:1px;" onclick="insertText('replytext', '[quote=<?php echo user::getUsername($message['poster']);?> date=<?php echo $message['post_date'];?>]<?php echo $message['message'];?>[/quote]');">
                            <i class="fa fa-reply" aria-hidden="true"></i></button>


<textarea class="form-control" rows="5" name="replytext" id="replytext"
                      style="width:100%;background-color:black;color:white;resize: none;"></textarea>



 <script>
        function insertText(elemID, replytext)
        {
            var elem = document.getElementById(elemID);
            elem.innerHTML += replytext;
        }
    </script>

When replytext contains new lines it will not fill the textarea with this value as it should do. Anyone have an idea how to fix this? It's related to replying a message with /n or br within it.

I've tested it. When there are no /n or br it is working.

Upvotes: 0

Views: 182

Answers (2)

halfer
halfer

Reputation: 20439

(Posted answer on behalf of the question author).

str_replace(PHP_EOL, '[br]',($_POST['replytext']))

This did the job. onClick function doesn't allow <br /> or any kind of new line.

Upvotes: 1

samAlvin
samAlvin

Reputation: 1678

The new line won't show in the view because you should convert the "new line" (\n) into html line break, which is <br />.

Try this:

function insertText(elemID, replytext)
{
    replytext = replytext.replace(/\r?\n/g, "<br />");
    var elem = document.getElementById(elemID);
    elem.innerHTML += replytext;
}

The replace(/\r?\n/g, "<br />") statement will replace the "new line" into HTML line break (<br />).

Upvotes: 1

Related Questions