Form handling onsubmit, onchange, onselect, onblur, onfocus

4. onselect

onselect is used to track when a user selects/highlights a text inside an input element or a textarea.

The code below is an example of the use of onselect. When the user selects any text inside the textarea, the function myFunction() is called.

 

<form>
           <label style="valign:middle" for="comment">Comments</label>
           <textarea id="comment" onselect="myFunction()" cols="50" rows="10"> </textarea>
</form>
<script>
     function myFunction() {
             var txtArea = document.getElementById("comment");
             var selectedText;   
             if (txtArea.selectionStart != undefined) {    
                  var startPosition = txtArea.selectionStart;
                  var endPosition = txtArea.selectionEnd;
                  selectedText = txtArea.value.substring(startPosition, endPosition);
             }
             alert("You selected : " + selectedText);
     }
</script>