1

Ok,

So I have the below JQuery code, which changes the background colour of a dt element, which has a specific class assigned:

var match = $('.matchedOn:contains("' + matchedString + '")');
                       $(match).html($(match).html().replace(matchedString, "<span 
   style='background-color:#FFFF00'>" + matchedString + "</span>"));

this is part of a $.each loop, and seems to work, if the loop goes through one iteration. For example, I have a data set that is return where there are two possible matches that need to be highlighted. To demonstrate this i'll mock up some example text, which will formualte the loop.

First Iteration : string matchedString = Hello

Second Iteration : string matchedString = World

both of these strings are within the same dt element, so for example:

'This is the Hello World example string'

The above JQuery code only seems to highligh the word 'Hello' and not the 'World'

Any ideas why? I debug and step through the code, and I can see that both matchedString vairables are set correctly.

EDIT Ok, sorry for the delay, i've managed to get hold of the code in question which will aid with the answer.

$.ajax({
           type: "POST",
           url: "Default.aspx/GetPopUpData",
           cache: false,
           data: JSON.stringify({ messageId: messageId, messageType: messageType, aml: true }),
           contentType: "application/json; charset=utf-8",

           dataType: "json",
           error: function (xhr) {

               var contentType = xhr.getResponseHeader("Content-Type");
               if (xhr.status === 401 && contentType.toLowerCase().indexOf("text/html") >= 0) {
                   window.location.reload();
               }
           },
           success: function (msg) {

               var mtData = msg.d[0];

               var tag13C = '';
               var tag33BSeqB = '';
               var tag50 = '';
               var tag50SeqB = '';
               var tag52 = '';
               var tag52SeqB = '';
               var tag53 = '';
               var tag54 = '';
               var tag55 = '';
               var tag56 = '';
               var tag56SeqB = '';
               var tag57 = '';
               var tag57SeqB = '';
               var tag58 = '';
               var tag59 = '';
               var tag59SeqB = '';
               var tag70 = '';
               var tag70SeqB = '';
               var tag72 = '';
               var tag72SeqB = '';
               var tag77B = '';
               var violationCount = '';

               if (messageType == "202") {
                   if (mtData["Tag13C"].length) {
                       tag13C = $.map(mtData["Tag13C"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag52"].length) {
                       tag52 = $.map(mtData["Tag52"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag53"].length) {
                       tag53 = $.map(mtData["Tag53"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag54"].length) {
                       tag54 = $.map(mtData["Tag54"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag56"].length) {
                       tag56 = $.map(mtData["Tag56"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag57"].length) {
                       tag57 = $.map(mtData["Tag57"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag58"].length) {
                       tag58 = $.map(mtData["Tag58"], function (ele) { return '<dd class=matchedOn>' + ele; }).join('');
                   }
                   if (mtData["Tag72"].length) {
                       tag72 = $.map(mtData["Tag72"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag50SeqB"].length) {
                       tag50SeqB = $.map(mtData["Tag50SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag52SeqB"].length) {
                       tag52SeqB = $.map(mtData["Tag52SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag56SeqB"].length) {
                       tag56SeqB = $.map(mtData["Tag56SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag57SeqB"].length) {
                       tag57SeqB = $.map(mtData["Tag57SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag59SeqB"].length) {
                       tag59SeqB = $.map(mtData["Tag59SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag70SeqB"].length) {
                       tag70SeqB = $.map(mtData["Tag70SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }
                   if (mtData["Tag72SeqB"].length) {
                       tag72SeqB = $.map(mtData["Tag72SeqB"], function (ele) { return '<dd>' + ele; }).join('');
                   }

                   $('<div class=message><pre><dl><dt>Transaction Reference:</dt><dd>' + mtData["Tag20"] +
                     '</dd><dt>Related Reference:</dt><dd>' + mtData["Tag21"] +
                     '</dd>' + (tag13C ? '<dt>Time Indication:</dt><dd>' + tag13C : '') +
                     '</dd><dt>Value Date / Currency Code / Amount:</dt><dd>' + mtData["Tag32"] +
                     '</dd>' + (tag52 ? '<dt>Ordering Institution:</dt><dd>' + tag52 : '') +
                     '</dd>' + (tag53 ? '<dt>Senders Correspondent:</dt><dd>' + tag53 : '') +
                     '</dd>' + (tag54 ? '<dt>Receivers Correspondent:</dt><dd>' + tag54 : '') +
                     '</dd>' + (tag56 ? '<dt>Intermediary:</dt><dd>' + tag56 : '') +
                     '</dd>' + (tag57 ? '<dt>Account With Institution:</dt><dd>' + tag57 : '') +
                     '</dd>' + (tag58 ? '<dt>Beneficiary Institution:</dt><dd>' + tag58 : '') +
                     '</dd>' + (tag72 ? '<dt>Sender to Receiver Information:</dt><dd>' + tag72 : '') +
                     '</dd><dt>Ordering Customer:</dt><dd>' + tag50SeqB +
                     '</dd>' + (tag52SeqB ? '<dt>Ordering Institution:</dt><dd>' + tag52SeqB : '') +
                     '</dd>' + (tag56SeqB ? '<dt>Intermidary Institution:</dt><dd>' + tag56SeqB : '') +
                     '</dd>' + (tag57SeqB ? '<dt>Account With Institution:</dt><dd>' + tag57SeqB : '') +
                     '</dd>' + (tag59SeqB ? '<dt>Beneficiary Customer:</dt><dd>' + tag59SeqB : '') +
                     '</dd>' + (tag70SeqB ? '<dt>Remittance Information:</dt><dd>' + tag70SeqB : '') +
                     '</dd>' + (tag72SeqB ? '<dt>Sender to Receiver Information:</dt><dd>' + tag72SeqB : '') +
                     '</dd>' + (tag33BSeqB ? '<dt>Currency / Instructed Amount:</dt><dd>' + tag33BSeqB : '') +
                     '</dd></dl></pre></div>').appendTo('#mt202');

               }

               var amlData = msg.d[1];

               if (amlData.length) {

                   $.each(amlData, function (index, item) {
                       var countries = ''; // intialize as empty string
                       var aka = '';
                       var identNum = '';
                       var listReason = '';
                       var names = '';

                       var reportCount = index + 1;

                       if (item.Countries.length) {
                           countries = $.map(item.Countries, function (ele) { return '<dd>' + ele; }).join('');
                       }

                       if (item.Aka.length) {
                           aka = $.map(item.Aka, function (ele) { return '<dd>' + ele; }).join('');
                       }

                       if (item.IdentNumbers.length) {
                           identNum = $.map(item.IdentNumbers, function (ele) { return '<dd>' + ele; }).join('');
                       }

                       if (item.ListingReasons.length) {
                           listReason = $.map(item.ListingReasons, function (ele) { return '<dd>' + ele; }).join('');
                       }

                       if (item.Names.length) {
                           names = $.map(item.Names, function (ele) { return '<dd>' + ele; }).join('');
                       }

                       var matchedItem = item.MatchedItem.trim();
                       var matchedTag = item.MatchedTag;
                       var senderBic = item.SenderBIC.trim();


                       var match = $('.matchedOn:contains("' + matchedTag + '")');
                       $(match).html($(match).html().replace(matchedTag, "<span style='background-color:#FFFF00'>" + matchedTag + "</span>"));




                   });

               }

               else {
                   $('<h2>Violation Report(' + amlData.length + ')</h2>').appendTo('#AMLresults');
               }
           }

       });

       $('#myModal').modal();

hope this helps

EDIT

So the first loop creates the single div with the content that contains the dt's with a class of matchedOn. the second loop which can contain more hits, is used to display the aml hits.

So in Tag58, the word 'This is a test case, please hightlight me' is written to the modal. then the aml loop has matchedTag, so first time around the hit is 'test case' and therefore any Tag containing the class of matchedOn, needs to have this test highlight, so on and so forth.

CSharpNewBee
  • 1,951
  • 6
  • 28
  • 64

3 Answers3

2

If you don't mind alternatives, then have a look WORKING FIDDLE

You can use RegExp to get you stuff done. I found it from my fav question highlight-a-word-with-jquery where @Andrew Hedges suggested -

function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="myClass">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');

For your code it, would be something like :-

var stringArray = ["Lorem", "Ipsum", "dummy"];

   function highlight_words(word, element) {
       var rgxp = new RegExp(word, 'g');
       var repl = '<span style="background-color:#FFFF00">' + word + '</span>';
       element.innerHTML = element.innerHTML.replace(rgxp, repl);
   }
   $.each(stringArray, function (index, value) {
       var matchedString = value;
       var element = document.getElementsByClassName('matchedOn');
       highlight_words(matchedString, element[0]);
   });

Even you can have a look jquery.highlight

Community
  • 1
  • 1
Shubh
  • 6,693
  • 9
  • 48
  • 83
  • There is a CaSeSeNsiTivitY issue here, using an array like `['I', 'Love', ' Ponies']` this method replaces "i love PONIES"-->"I Love Ponies" - a stylistically important difference. Imagine if you wanted to hilight words like "and"; having every "And" capitalized makes for a stylistically spam-like read. – Joel Peltonen Oct 28 '13 at 12:06
  • Shubh, i ran through your code, and i couldn't get it to work. See above for the content i am trying it against. I think the problem is, is that i don't have an array of strings, i have one string at a time in a loop, matching against a single element. – CSharpNewBee Oct 28 '13 at 15:17
0

I think there is a problem in your loop... It's difficult to say as we don't see the html or the loop that you have.

I started to reproduce the issue and first made it like this - http://jsfiddle.net/h7Zf2/1/. I inserted an alert to indicate that it kinda stops the first iteration (only one word is highlighted) and after clicking the alert - the second word highlights.

Which led me to a possible solution to your problem. I keep the strings in an array and iterate the text to replace the words from the array: http://jsfiddle.net/h7Zf2/2/

var matchedString = ['ipsum', 'dolor', 'odio'];
for( var i = 0; i <= matchedString.length; i++ ) {
    var match = $('.matchedOn:contains("' + matchedString[i] + '")');
    match.html(match.html().replace(matchedString[i], "<span style='background-color:#FFFF00'>" + matchedString[i] + "</span>"));
}

Hopefully you'll find something useful here :)

skip405
  • 6,119
  • 2
  • 25
  • 28
  • Skip405 - thanks for helping out with this. I'll try and put something together, which better explains my issue. Give me an hour or so, as I'll need help from the c# guys to get the info – CSharpNewBee Oct 28 '13 at 11:30
0

Shubh Dasgupta's answer is good enough, but there is a CaSe SeNsiTivitY issue there, using an array like ['I', 'Love', ' Ponies'] it would replace i LOVE Ponies with I Love Ponies - a stylistically important difference.

Anyway, here's another regex-regurgitation that does not interfere with case: jsfiddle.net/h7Zf2/4 That solution is basically copied from https://stackoverflow.com/a/1230491/694325

There are two different methods used there, test with actual content to see which one would be better for you. Also depends a lot on target language. For english this is easier than for German or Finnish for example: For hilighting Leben and Partner, what should happen with Lebensabschnittpartner!? Or in english Love vs Lovely: hilight or not?

Community
  • 1
  • 1
Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100