1

I want to do text editor and change the texts which is inside the content editable elements and also selected by the user.

my question is: How to get the selected texts inside the content editable elements?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"  src="D:\JQueryPath\jquery-3.1.1.js">         </script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#show").click(function(){
            //alert("selected texts");
            });
        });
    </script>
</head>
<body>
<div  id="textEditor" style=" border:solid 1px #D31444" contenteditable="true" ></div>
<p></p>
<button id="show">show selected elements</button>
</body>
</html>
  • http://stackoverflow.com/questions/13285877/html-content-editable-div-select-text-event/13286950#13286950 you can refer to this link – Anshul Feb 28 '17 at 10:22
  • It's really unclear what you are trying to do. When you click the show btn what are you trying to do specifically? – David Brewer Feb 28 '17 at 10:31
  • if I click the button I want to alert the selected texts inside the (div)content editable element @DavidBrewer – Vengaaya Pakkoda Feb 28 '17 at 10:34

3 Answers3

2

This should get you started, although you will need to consider expanding on this code to cater for situations where someone selects outside of your text area and when someone presses the button and nothing is selected.

Oh, and I have console logged the output rather than alerted it.

$(document).ready(function(){
  $("#show").click(function(){
    range = window.getSelection().getRangeAt(0);
    console.log(range.toString());
  });
});
David Brewer
  • 131
  • 5
0

You can use window.getSelection() method.

lavish
  • 2,154
  • 1
  • 10
  • 9
  • I am beginner and I don't know how to use window.getSelection() method. I searched but still I didn't find any correct answers which using this window.getSelection() method – Vengaaya Pakkoda Feb 28 '17 at 10:29
  • When the button is clicked, you can use this method inside the handler to retrieve currently selected text. and can show this in alert box. – lavish Feb 28 '17 at 10:42
0
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"  src="D:\JQueryPath\jquery-3.1.1.js"> </script>
  <script type="text/javascript">
    $(document).ready(function(){
        $("#show").click(function(){
        alert(window.getSelection().toString());
        });
    });
</script>
</head>
<body>
<div  id="textEditor" style=" border:solid 1px #D31444"contenteditable="true" ></div>
<p></p>
<button id="show">show selected elements</button>
</body>
</html>