Differentiate Enter from Shift Enter in a textarea, getting the value via javascript

Question:

I have a textarea outside of a form:

<textarea name="textoOriginal">

Inside this textarea , I can type a text, and ENTER or SHIFT + ENTER for line break. When I get the value of the element, I need to differentiate what was ENTER and what was SHIFT + ENTER , but I get them all with ASCII code 10

Test I took:

Html:

<textarea class="form-control" name="textoOriginal" rows="15"></textarea>    

Javascript:

document.querySelector('textarea[name="textoOriginal"').value.split('')
.forEach( function (value) {
             console.log(value + ' corresponde a:'+value.charCodeAt(0));
});

Answer:

Here's the code to get the desired result:

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

$('textarea').keyup(function (event) {
       if (event.keyCode == 13 && event.shiftKey) {
           var content = this.value;
           var caret = getCaret(this);
           this.value = content.substring(0,caret)+"\n"+content.substring(caret,content.length-1);
           event.stopPropagation();
           
      }else if(event.keyCode == 13)
      {
          $('form').submit();
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form><textarea></textarea></form>

I posted it here to help you, but the credit is all for the guy who answered this question: https://stackoverflow.com/questions/6014702

PS: Trying a local HTML, even without this code the textarea was skipping the line without submitting the form, I couldn't understand why…

Scroll to Top
AllEscort