tags:

views:

35

answers:

3

I'm trying to replace a string (Completed) with another string (C) that resides in a tablecell in some HTML being returned from a jquery POST. The POST is working correctly and I'm able to find my string, but setting it to the new string doesn't seem to do anything (no errors, but the original string is rendered in my page). Below is my code. Any ideas? Note the commented-out line is what I was originally trying to use to do the find/replace, and then used the indexOf when I couldn't get it working:

$.post(myURL, "",  function(data){
   $(data).find("#ReportOutput tr td").each(function(index) {
      //$(":contains('Completed')", this).css('backgroundColor', '#006600').css('color','white').html("C");
      // the above is not working, not sure why.  Below is workaround
      if ($(this).html().indexOf("Completed") > 0) {
        alert("found it. " + $(this).html());
        $(this).html("C");
      } 
   });
   $(data).find("#ReportOutput").appendTo('#divdetails');
});

divdetails is just a div where I am displaying the HTML. No errors when running this, and the alert happens showing it found my string, but when the html loads into the div it shows the "Completed" string.

Can anyone point out what I'm doing wrong?

Thanks

A: 

If you attach the result to the DOM before replacing I think it will work:

$.post(myURL, "",  function(data){
   $(data).find("#ReportOutput").appendTo('#divdetails');   
   $("#ReportOutput tr td").each(function(index) {
      if ($(this).html().indexOf("Completed") > 0) {
        $(this).html("C");
      } 
   });
});

The problem is that you are trying to replace on a string which is not part of the DOM yet, so most likely it will only work on a copy, never editing the original data string.

Mikael Svenson
Thanks. That gets me further, although now I'm seeing something strange. Within the .each loop, the context is the td, correct? So when we say "$(this).html("C");" we are setting the html of the td to C, right? If I run that code, it replaces all the HTML with "C", and when my "divdetails" appears all it has within it is a "C". Does that make sense?
Steve
Disregard, use-error on my end. I had another ReportOutput table, and once I accessed the right one everything works great. Thanks for the help.
Steve
A: 

Try replacing this:

$(":contains('Completed')", this).css('backgroundColor', '#006600').css('color','white').html("C");

with this:

$(this).filter(":contains('Completed')").css('backgroundColor', '#006600').css('color','white').html("C");
ironsam
A: 

Another note, if "Completed" comes first in the string, your if statement wont happen. Use -1 as your comparison instead.

if ($(this).html().indexOf("Completed") != -1) {
wowo_999