views:

303

answers:

2

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?

Thanks!

+1  A: 

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>');
});
Philippe Leybaert
+1  A: 

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

SolutionYogi
Worked perfectly! +1
peehskcalba