0

I'm trying to highlight a matched name from user search. If the user search is in the array, the matched array item should be highlighted in the text area. How to accomplish this? Here is what I have so far.

function search() {
  var list = $('#textArea').val();
  var listArr = list.split(',');
  $('#textArea').html(listArr);
  var userSearch = $('#nameSearch').val();

  var i = 0;
  while (listArr[i]) {
    var res = listArr[i].indexOf(userSearch);
    if (res !== -1) {
      console.log(userSearch + ' is on the list.');
      //highlight matched name in textArea
    }
    i++;
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <textarea class="nameList" name="names" id="textArea" cols="30" rows="10">joe, monica, harry, hanna</textarea>
</div>
<input type="text" id="nameSearch" />
<button onclick="search()">Search By Name</button>

Here is a link to the codepen:

Codepen

Ramesh
  • 2,297
  • 2
  • 20
  • 42
  • Try to check out here: https://stackoverflow.com/questions/4705848/rendering-html-inside-textarea – Tomas Aug 27 '18 at 18:12

1 Answers1

0

To match the fist occurrence you need to focus the textarea first and then use setSelectionRange.

Also since setSelectionRange is not jQuery method you would need to access the html element via the 0 index e.g. $txt[0].setSelectionRange

Try something like this:

function search() {
  var $txt = $('#textArea')
  $txt.focus()
  var list = $txt.val();
  var search = $('#nameSearch').val();
  var index = list.indexOf(search);
  $txt[0].setSelectionRange(index, index + search.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <textarea class="nameList" name="names" id="textArea" cols="30" rows="10">joe, monica, harry, hanna</textarea>
</div>
<input type="text" id="nameSearch" />
<button onclick="search()">Search By Name</button>
Akrion
  • 18,117
  • 1
  • 34
  • 54