views:

287

answers:

4

OK I am just starting out with jQuery.

I have a page with a table of date-values. Each is wrapped in a tag which I can find with $('mytag'). <mytag>2009-10-31</mytag>

How, using Jquery, would I

  1. take each of the source values and
  2. pass it to a Javascript function
  3. then replace that source value within the table with the result of the function calculation.

So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>

I have the Javascript function written. My question is the jQuery syntax to pass the individual value.

A: 
$('mytag').each(function (index,tag) {
    $(tag).text( myFunc($(tag).text()) );
});
Rich
A: 
$("mytag").each(function() {
   $(this).html("Very Late");

});
Luca Matteis
+6  A: 

Firstly, you will need an element selector, e.g.

$('table')

Will select all <table> elements in your html. So,

$('mytag')

will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors

Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:

$('mytag').each(function(){
    //function code goes here
});

(See http://docs.jquery.com/Utilities/jQuery.each)

The function in this case is called an Anonymous function

Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)

$('mytag').each(function(){
    $(this).text()
});

Note: if it were an input element then you would have used .val()

Passing it to a function is easy:

    ...
    MyFunction($(this).text());
    ...

The text() function has an overloaded implementation which allows you to set the text if you pass a value:

    $(this).text(someval);

So, we can factor this into our code

    ...
    $(this).text(MyFunction($(this).text()));
    ...

Making our final code block:

$('mytag').each(function(){
    $(this).text(MyFunction($(this).text()));
});
James Wiseman
Thanks, this worked like a charm, and your explanation was thorough and clear.
George W
A: 
$('mytag').each(function() {
  $(this).text(someFunction($(this).text()));
});


But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:

jQuery.timeago.settings.allowFuture = true;

...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Ryan McGeary