peehskcalba
peehskcalba

Reputation: 181

How to use jQuery to convert text to email links

I have an HTML table with one column being email addresses; spambot issues aside, I'd like to convert each <td> element in this column to a mailto: link.

Here's what I've got:

$("table.data tbody tr td:last").each(function() {
    var email = $(this).val();
    $(this).html('<a href="mailto:' + email + '">' + email + '</a>');
});

And this is the table (sample):

<tr>
    <td>Joe</td>
    <td>Shmoe</td>
    <td>[email protected]</td>
</tr>

What's going wrong?

Upvotes: 1

Views: 1648

Answers (2)

SolutionYogi
SolutionYogi

Reputation: 32243

Your jquery selector is wrong.

When you do 'table.data tbody tr td:last' it will only select the last cell of the last row.

What you need to do is something like:

$(document).ready(
    function()
    {
        //For each row...
        $('table.data tbody tr').each(
            function()
            {  
                //...find the last cell.
                var lastCell = $(this).find('td:last');
                $(lastCell).html('<a href="mailto:' + $(lastCell).text() + '">' + $(lastCell).text() + '</a>');
            }
        );
    }
);

Working demo: http://jsbin.com/umiza Code: http://jsbin.com/umiza/edit

Upvotes: 2

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

You should use .text() instead of .val():

$("table.data tbody tr td:last").each(function() {
    var email = $(this).text();
    $(this).html('<a href="mailto:' + email + '">' + email + '</a>');
});

Upvotes: 1

Related Questions