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

Asked

Viewed 404 times

3

I have a textarea out of a form:

<textarea name="textoOriginal">

Within that textarea, I can type a text, and ENTER or SHIFT + ENTER for line breaking. When I take the value of the element, I need to differentiate what was ENTER and what was SHIFT + ENTER, but I receive 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));
});
  • 1

    Curiosity: what would be the application of this?

  • The internal html generated for both cases is the same as the visual effect. Why differentiate in code?

  • You can do this using the events: onkeydown onkeypress onkeyup

1 answer

1

Follow 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 it’s all the credit of the guy who answered that 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...

  • Very good, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.