Jaztingo Jaztingo - 1 year ago 149
Javascript Question

difference between jQuery keypress and javascript onkeypress

What's difference between jQuery keypress and JavaScript onkeypress?

When I'm trying to get cursor's start/end position in textbox/textarea in jquery I must use this one (using caret plugin)

var stratposition = this.caret().start;
var endposition= this.caret().end;

but when onkeypress

<textarea onkeypress="return makeGeo(this,event);"></textarea>

function makeGeo(ob,e) {
var startPos = ob.selectionStart;
var endPos = ob.selectionEnd;


Is there any way to get cursor's positions in jquery without caret plugin?

Answer Source

In the jQuery event handler, simply use this.selectionStart and this.selectionEnd:

$("#sometextbox").keypress(function(e) {
  var startPos = this.selectionStart;
  var endPos = this.selectionEnd;
  console.log(startPos, endPos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<textarea id="sometextbox"></textarea>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download