简体   繁体   中英

How to get Selected Text in Textbox

im using a hyperlink here and on click event of the hyperlink i want to copy the selected text (which i have selected using the mouse pointer or highlighted text) inside the text box using the java script i want only selected text in the text box which i select or highlight from mouse pointer.my java script is working but it copy the full text of div

<li><a href="#" onclick="JAVASCRIPT:return Edit();">Candidate Name</a> </li>
<script type="text/javascript">
    function Edit() {
        alert("hiii");
        document.getElementById('<%=txtbox.ClientID%>').value = document.getElementById('<%=divtext.ClientID%>').innerHTML;
         return true;
    }
</script>
<div>
    <asp:TextBox ID="txtbox" runat="server"></asp:TextBox>
</div>
<div id="divtext" runat="server">
    TCS Infosys Wipro HP HCL Microsoft Facebook Facebook Facebook 
</div>

Try this

<!DOCTYPE html>
<html>
<script type="text/javascript">
 function getSelectionText(divID) {
    var selectedText = "";
    if (window.getSelection) {
        var sel = window.getSelection();
        var div = document.getElementById(divID);

        if (sel.rangeCount) {
            // Get the selected range
            var range = sel.getRangeAt(0);

            // Check that the selection is wholly contained within the div text
            if (range.commonAncestorContainer == div.firstChild) {
                var selectedText = range.toString();
               }
          }
       }
     return selectedText;
   }

   function Edit() {
        var selectedText = getSelectionText("divtext")
        document.getElementById("txtbox").value =  selectedText;
        return true;
   }
 </script>
<body>
        <li><a href="#" onclick="JAVASCRIPT:return Edit();">Candidate Name</a> </li>
         <div>
            <input type="text" ID="txtbox" />
        </div>
        <div id="divtext">
            TCS Infosys Wipro HP HCL Microsoft Facebook Facebook Facebook 
        </div>
 </body>

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