May 5, 2009

jQuery, Selecting the Previous Element With Filtering

Recently I was looking for a solution to this problem. My HTML looked like this:

<a class="file" href="download/876243.pdf">876243.pdf</a>
<a class="tagcontrol" id="876243.pdf">tag</a>
<a class="tag" href="index.php?tag=test">test</a>
<img class="delete" title="remove this tag" src="img/tag-del.png" />
Here is how the tags will look.

Here is how the tags will look.

The idea being that you would click the image with the “delete” class and submit an ajax call to delete the tag for that file in a Folksonomy system. I had the hardest time trying to figure out how to select the tagcontrol link, I needed to acquire it’s ID for one of the data variables in the ajax call. The answer came from prevAll(). With only the “this” reference from the clicked image, you can find and select the most previous “a” element that has the “.tagcontrol” class.

This line allowed me to find only the most previous element that had the attribute of “a” anchor tag with a class of “tagcontrol”.

$(this).prevAll("a.tagcontrol").attr("id");

Here is the complete function:

$(".delete").live("click", function() {
    var thebutton = $(this);
    var todelete = $(this).prev().html();
    var file = $(this).prevAll("a.tagcontrol").attr("id");
    $.ajax({
        type: "GET",
        url: "tag.php",
        data: '?file=' + file + '&amp;delete=' + todelete,
        success: function(){
            thebutton.prev().remove();
            thebutton.remove();
        }
    });
    return false;
});

This came in handy for me using the search expression feature of the prevAll() function. It’s official purpose is “Find all sibling elements in front of the current element”. However that may be a little hard to understand. Hopefully my little demonstration will help you employ this feature of jQuery.

February 15, 2008

What Your Company Needs to Grow

When you work for a company, some days you feel owned. You feel maybe as if you are an asset for “the man”. But on those days when you realize that you are an autonomous agent able to do as much as your inner resolve allows, then you are a person who is indeed useful. When we take into account that companies are just bodies of people aligned together in similar goals, then we can work in harmony towards the greater good. Adam Smith in his quintessential tome on economics, “The Wealth of Nations” sums up nations and economies very simply…