Total Pageviews

2018/05/06

[JavaScript] Utilize window.getSelection to get selected text

Problem
If I would like to get the selected text from a TextField via JavaScript, how to do it?

How-To

You can make good use of window.getSelection to fulfill this requirement.

HTML code snippet:

       <div class="row">
           <div class="col-sm-offset-1 col-sm-10">
             <div class="form-group">
               <label for="operaName" class="control-label">連續劇</label>
               <input type="text" class="form-control input-lg" id="operaName" data-ng-model="operaName" 
                      data-ng-mouseup="showOperaSelectedText()" >
             </div>
             <div class="form-group">
              <label class="control-label">起訖</label>
              <span> {{operaNameFromIndex}} ~ {{operaNameToIndex}}</span>
             </div>
             <div class="form-group">
                 <label class="control-label">選擇文字</label>
                 <span> {{operaNameSelected}}</span>
             </div>
           </div>
       </div>


JavaScript code snippet:
     $scope.operaName = "又,吳海英";
     $scope.operaNameFromIndex = 0;
     $scope.operaNameToIndex = 0;
     $scope.operaNameSelected = '';
      
     $scope.showOperaSelectedText = function() {
     // if selected
     if (window.getSelection) {
          // get selected text
          $scope.operaNameSelected = window.getSelection().toString();
          // get from index
          $scope.operaNameFromIndex = $('#operaName').prop('selectionStart');
          // get end index
         $scope.operaNameToIndex = $('#operaName').prop('selectionEnd');
         }
     }


Screenshot:


No comments: