1

How does one change the HREF value of a table using the following

<table id="tbl">
<td>
<a href="1">test1</a>
<a href="2">test2</a> 
<a href="3">test3</a>
</td>
<td><label>foo1</label></td>
<td><label>foo2</label></td>
<td><label>foo3</label></td>
</table>

To this:

<table id="tbl">
<td>
<a href="1foo1">test1</a>
<a href="2foo2">test2</a> 
<a href="3foo3">test3</a>
</td> 
<td><label>foo1</label></td>
<td><label>foo2</label></td>
<td><label>foo3</label></td>
</td>
</table>

Essentially I am relabling the anchors based on data from another column. I would prefer to use jquery. THanks!

InCode
  • 503
  • 3
  • 8
  • 25
  • 1
    This answer is also available http://stackoverflow.com/questions/4345427/jquery-set-and-get-href – Caimen Mar 28 '14 at 18:46
  • 1
    No. I know how to change the href. I don't know how to change it based on the other columns text. – InCode Mar 28 '14 at 18:46

2 Answers2

3
$("#tbl td a").each(function() {
    var oldVal = $( this ).attr( "href" );
    $( this ).attr( "href" ,  oldVal + "foo" + oldVal);
});
Anri
  • 1,706
  • 2
  • 17
  • 36
3

You can use:

$('#tbl td a').each(function(i) {
    var text = $('#tbl label').eq(i).text(),
        oldHref = $(this).attr('href');
    $(this).attr('href', oldHref + text);
});

Fiddle Demo


If you want to remove the trailing spaces inside the text of your label, you can use $.trim():
$('#tbl td a').each(function(i) {
    var text = $('#tbl label').eq(i).text(),
        oldHref = $(this).attr('href');
    $(this).attr('href', oldHref + $.trim(text));
});
Felix
  • 37,892
  • 8
  • 43
  • 55
  • +1 for `eq()`. You can make it even more generic by using `$('label', $(this).closest('table'))` as a label selector, so it doesn't depend on the table's id. – blgt Mar 28 '14 at 19:20
  • This looks promising. It works on IE8 but not on IE9. IE9 gives me the right url but it adds spaces within the "text" variable. – InCode Mar 31 '14 at 15:03