0

i m 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>
SANDEEP
  • 1,062
  • 3
  • 14
  • 32
  • [check this](http://jsfiddle.net/dKaJ3/2/) http://stackoverflow.com/questions/4652734/return-html-from-a-user-selection/4652824#4652824 – Damith May 08 '13 at 10:38
  • Thanks Damith,but i want my context menu only on selected div area not full page can u help me on this. i mean to say that i want right click on divtext not other part of page. – SANDEEP May 08 '13 at 12:28

1 Answers1

0

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>

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
  • Hi Navnath,Thanks a lot. but i want my context menu only on selected div area not full page can u help me on this. i mean to say that i want right click on divtext on other part of page – SANDEEP May 08 '13 at 12:24
  • @SANDEEP...Check my new solution. – Navnath Godse May 08 '13 at 13:00