简体   繁体   中英

How to get position of cursor in a textbox VB.NET Web Form

I have a textbox and I want to know the position of the cursor (preferably as a character index in textbox.Text) when a button is clicked and I want to do this in the server side using VB.

<asp:TextBox ID="txtboxExplanation" runat="server" Height="530px" TextMode="MultiLine" Width="500px" MaxLength="600"></asp:TextBox>

Thanks!

Here is how you can achieve what you are looking for. What we will do is when the textarea (multi line textbox) loses focus (onblur), we will try to get the caret position and then place it into a hidden field, which you will then have access to on the server.

On your page, you need to include some javascript - getCaret function taken from [here][1]

<script type="text/javascript">

function saveCaretPos(txt) {
  document.getElementById('<% =CaretPos.ClientID %>').value = getCaret(txt);

}
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; 
}

</script>

Then add a hidden input field inside of your form, so you can easily send your caret position to the server.

 <asp:HiddenField runat="server" ID="CaretPos" />

Then adjust your Multiline textbox to this:

<asp:TextBox ID="txtboxExplanation" runat="server" Height="530px" TextMode="MultiLine" Width="500px" MaxLength="600" onblur="saveCaretPos(this);"></asp:TextBox>

Now, when you post back to the server, you can access the caret position, like this

Dim mycaretpos As Integer = CaretPos.Value        ' mycaretpos now contains the position the caret was in when the form was submitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM