views:

1250

answers:

1

Hi i'm trying to use jQuery/javascript to make my life easier. I'm trying to use it to auto fill in the various html elements with the name of the place and country which comes from the file name of the image. Below is a sample of some of the html i have to work with:

<div class="boxgrid">
<a href="gallery/angkor - cambodia.jpg" title="[PLACE] - [COUNTRY]">
  <img src="gallery/thumbs/angkor - cambodia.jpg" alt="[PLACE] - [COUNTRY]" width="100" height="100"/>
</a>
  <div class="boxcaption">
    <span class="place">[PLACE]</span>
    <span class="country">[COUNTRY]</span>
  </div>
</div>

Imagine this block of html is repeated multiple times for every image in the gallery so i assume .each() will need to be used.

The idea is that [NAME OF PLACE] and [NAME OF COUNTRY] should be filled in with the image's file name using the - (dash) as the delimiter between the two values. How can I accomplish this with jQuery/javascript? (i realise i should use a server side language or go about this another way but this is what i'm restricted to)

As a bonus the first letter of each of the values should be capitalised, for example Angkor - Cambodia .

Thank you, any help would be much appreciated.

+2  A: 

Here's the full code with trimming and capitalization of the first letter for Place and Country.

String.prototype.capitalize = function(){
    return this.replace(/\S+/g, function(a){
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
    });
};

$(function(){
 $('.boxgrid').each(function(){
    var placeCountry = $(this).find('img').attr('src')
                            .replace('gallery/thumbs/','')
                            .replace('.jpg','').capitalize();

    var place = $.trim(placeCountry.split('-')[0]); 
    var country = $.trim(placeCountry.split('-')[1]);
    $(this).find('a').attr('title',placeCountry);
    $(this).find('img').attr('alt',placeCountry);
    $(this).find('.place').html(place);
    $(this).find('.country').html(country);
 });
});
Jose Basilio
I would like to thank you very much for your time and effort in solving this problem, I will try the code now. I would like to add that although this may seem a very specific problem i think it may help others to understand how to use existing information on the page and repurpose it for other uses.
ritch0s
i get an error: $(this).find("img").attr("src").replace("gallery/thumbs/", "").replace(".jpg", "").capitalize is not a function
ritch0s
The error seems to be solved by putting the capitalize function before the rest of the code. Thanks.
ritch0s
Uhm. It works for me as is. In both FF and IE.
Jose Basilio
1 thing i've added is trim to get rid of the whitespace from the place and country variables. var place = $.trim(placeCountry.split('-')[0]); var country = $.trim(placeCountry.split('-')[1]);
ritch0s