jQuery: selectionStart returns undefined

5.8k views Asked by At

Situation

browser

Google Chtome 69

html

<textarea id="message" name="message">
    // input some messsage
</textarea>

js(jQuery)

$(function () {
  $("#message").on("keydown keyup keypress change", function () {
      //this part runs correctly
  })

  $('#message').on('keydown', function (e) {
    if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
      var $textarea = $(this);
      var sentence = $textarea.val();
      var position = $textarea.selectionStart;
      var length = sentence.length;
      var before = sentence.substr(0, position);
      var after  = sentence.substr(position, length);
      sentence = before + "\n" + after;
    }
  });
});

When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.

Needs

Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.

js

function fnCancelEnter()
{
  if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
    if (window.event.keyCode == 13)
      {
        return false;
      }
  }
  return true;
}

However, in this textarea, I want to enable user to add a break line by pressing Enter key.

I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.

1

There are 1 answers

0
kntrieu On BEST ANSWER

Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.