Search code examples
javascriptjqueryhtmltextareacursor-position

JavaScript: add string onkeypress at curser position in textfield


I have the following code:

<!DOCTYPE html>
<html>
<head>
<script>function handleEnter(e){messageVar=document.form.main_text.value,13==e.keyCode&&(document.form.main_text.value=messageVar+"<br>")}</script>
</head>
<body>

<form name="form">

<textarea style="width:300px;height:200px;" name="main_text" onkeypress="handleEnter(event)">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</textarea><br><br>

</form>

</body>
</html>

When clicking the return key on my keyboard it inserts the string <br> in the textarea. Unfortunately the string will get inserted at the end of the textarea content and not at the cursor position.

Does anybody know what I need to do to insert the string <br> at cursor position?


Solution

  • This solution should do the job !

    function handleEnter(e){
      var myElement = document.form.main_text;
      // Get the caret position
      var position = document.form.main_text.selectionStart;
    
      if (e.keyCode===13) {
        // Disable the default action of the Enter button (make a line break)
        e.preventDefault();
        // Set the new value = Text Before the cursor + "<br>" + text after the cursor
        myElement.value = myElement.value.substring(0,position)+"<br>"+myElement.value.substring(position)
        // Set the caret at the new position after the <br> tag
        myElement.setSelectionRange(position+4,position+4);
      }
    }