Using jQuery to copy the value from the original image file name for processing and pasting into html?

Hi i am trying to use jQuery / javascript to make my life easier. I am trying to use it to auto-populate various html elements with a place and country name that comes from the image file name. Below is an example 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 that this html block is repeated multiple times for each image in the gallery, so I guess I need to use .each ().

The idea is that [LOCATION NAME] and [COUNTRY NAME] should be filled with the image file name using - (dash) as a separator between the two values. How can I accomplish this using jQuery / javascript? (I understand that I have to use a server-side language or go about it differently, but this is what I'm limited to)

As a bonus, the first letter of each value must be capitalized, eg Angkor - Cambodia.

Thanks, any help would be greatly appreciated.

+1


a source to share


1 answer


Here's the complete code with trim 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);
 });
});

      

+2


a source







All Articles