0

I have a JQuery datatable, that display a search string column. When the user hovers over the row, I want to highlight the corresponding text within a text area.

For example, if the text area contains the following:

this is a place of beauty

And my Datatable row contains:

this is a place

then the text area portion needs to be highlighted.

I've used a couple of plugins, but they only seem to cater, for single word matches, whereas I need to do a sentence search, if you will.

The code I have is :

  $('#tblHitData tbody').on('mouseover', 'td', function() {

        var data = oHitData.row($(this).parents('tr')).data();

        var searchString = data['SearchString'];

        if ($("#message:contains('" + searchString + "')")) {
            $('#message').highlight(searchString);
        };

  });
CSharpNewBee
  • 1,951
  • 6
  • 28
  • 64

1 Answers1

1

This returns a jQuery object:

$("#message:contains('" + searchString + "')")

Objects in JavaScript are always "truthy," so your if statement will always run.

Instead, you can use the each function on the selector itself.

Update

You can't use :contains on a textarea. Instead, you can search for the string within the textarea's val(), using indexOf().

var searchString= 'is a test';

$("div:contains('" + searchString + "')").each(function() {
  $(this).css('background', 'yellow');
});

if($('#message').val().indexOf(searchString) >- 1) {
  $('#message').css('background', 'yellow');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>this is a test</div>
<div>this might possibly be a test</div>
<div>let's give lois a test</div>
<div>this is most definitely a test</div>
<textarea id="message">
  this is a test
</textarea>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
  • Yeah, searching on a div isn't the problem. The text is inside a textarea, for which I simply cant get it to work. – CSharpNewBee Dec 12 '14 at 16:46
  • Oh! Sorry I didn't associate "text area" with a `textarea` object. I've updated my answer. – Rick Hitchcock Dec 12 '14 at 17:06
  • Ok, so this appears to set the entire TextArea yellow. Not the matching string. – CSharpNewBee Dec 15 '14 at 10:44
  • In your example, the textarea is also completly Yellow. In my table I want to hover over some text, and highlight the matching text in the textarea, and only that text – CSharpNewBee Dec 15 '14 at 10:48
  • You have a couple options: 1) Use a contenteditable div instead of a textarea; 2) Place a div behind the textarea and style it: http://stackoverflow.com/questions/12005057/jquery-javascript-highlight-a-part-of-text-from-input-or-textarea – Rick Hitchcock Dec 15 '14 at 14:30