jQuery: Get the cursor position of text in input w

2019-01-04 02:09发布

This question already has an answer here:

Is there any way in jQuery to get the current cursor-position in an text input without doing ugly browser specific code?

Like in:

<input id="myTextInput" type="text" value="some text" >

the cursor being after the "x" of "some text", I can get "8"?

4条回答
家丑人穷心不美
2楼-- · 2019-01-04 02:35

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

查看更多
做个烂人
3楼-- · 2019-01-04 02:40

A warning about the Jquery Caret plugin.

It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

查看更多
不美不萌又怎样
4楼-- · 2019-01-04 02:51

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

You can try out a demo here.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

查看更多
狗以群分
5楼-- · 2019-01-04 02:57

just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea. You can use it for textbox also.

查看更多
登录 后发表回答