The King is The King is - 5 months ago 9
jQuery Question

How to add a break-line in a textarea by clicking a link

I have search and all I could get is just changing the value of the textarea.

What I really want is when I click a link, it adds a new line-break to my textarea

<a href="javascript:;"add new line break</a>
<script>
$("a").click(function(){
//run code to add new break line
});

Answer

You can try something like this to add a line break at the end of the textarea :

f.e :

$("#btn").click(function(){
    $("#text").val($("#text").val()+"\n");
});

https://jsfiddle.net/oqaawo2r/

EDIT :

Something like this should do the trick :

$("#btn").click(function() {
    var index = $('#text').prop("selectionStart");
    var text= $('#text').val();
    var r=text.slice(0, index) + "\n" + text.slice(index);
    $("#text").val(r);
});

https://jsfiddle.net/kke67x9f/

Comments