2

I'm trying to get the character position of a click inside an input. Meaning that if my input has the text abcdef and I click between the b and the c my click listener (inside my input element) would return 2.

Nate
  • 7,606
  • 23
  • 72
  • 124

2 Answers2

3

$(document).on("click", function() {
      
        var $txt = $("#txt");
        var caretPos = $txt[0].selectionStart;
        var textAreaTxt = $txt.val();
       console.log(caretPos);
        console.log(textAreaTxt[caretPos]);
    });
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
</head>
<body>
<input id="txt" rows="15" cols="70"/>

</body>
</html>

Something like this? this essentially builds off quik_silv anwser you get the index value of the cursor then get the value of the text field and retrieve a value by the index it's on a button click but could be easily changed

$("#btn").on('click', function() {
    var $txt = $("#txt");
    var caretPos = $txt[0].selectionStart;
    var textAreaTxt = $txt.val();

    console.log(caretPos);
    console.log(textAreaTxt[caretPos]);
});
Community
  • 1
  • 1
Jonathan Newton
  • 832
  • 6
  • 18
1
//Try this

<input id="text" type="text" value="EXAMPLE" size="20" />
<script type="text/javascript">
    document.getElementById('text').addEventListener('click', function() {
    var length = this.value.length;
    var x =length-(length-this.selectionStart)
alert(x);
},
false);
Ganesh Devkate
  • 109
  • 1
  • 13