I have recently had to use jQuery to add some copy to a column in a table. The problem I had was identifying which column. In my case the each column had it’s own class eg: –
<thead>
<tr>
<th class=”column-1″>Model Number</th>
<th class=”column-2″>Height</th>
<th class=”column-3″>Width</th>
<th class=”column-4″>Enquiry</th>
</tr>
</thead>
What I wanted to do was add some html (including a variable that represented the enquiry form) to the Enquiry column, in this case it would be column-4.
This all looks pretty simple if you have the same number of columns for each table, but I didn’t, so I needed to look for the enquiry column, then mark it to add the code to. The workflow is therefore: –
- Find the column class where the column header (th) has the text Enquiry
- Mark that column class by adding an extra new class, in this case enqcol
- Add the additional code to the column with the enqcol class
Our code is as follows: –
var classname = $( “th:contains(‘Enquiry’)” ).attr( ‘class’ )
$(‘table tr td.’+ classname).addClass(‘enqcol’);
$(‘td.enqcol’).html(‘<a href=\”‘ + enquiryform + ‘\”><img src=\”http://simongriffiths.name/images/enquriy-icon.png\” alt=\”Quick Quote\” width=\”15\” border=\”0\”></a>’);
The first line defines a variable called classname. This is set as the name of the class of the table header (th) that contains “Enquiry”. The result in the example above would be that classname=”column-4″.
The second line uses the variable above. It adds the class enqcol to any table cell (td) with the classname=”column-4″. Therefore at this point our code would be modified by jQuery to become: –
<thead>
<tr>
<th class=”column-1″>Model Number</th>
<th class=”column-2″>Height</th>
<th class=”column-3″>Width</th>
<th class=”column-4 enqol”>Enquiry</th>
</tr>
</thead>
The last line essentially looks for a table cell with the class enqcol (td.enqcol) and adds the html shown. In this case we are adding: –
<a href=\”‘ + enquiryform + ‘\”><img src=\”http://simongriffiths.name/images/enquriy-icon.png\” alt=\”Quick Quote\” width=\”15\” border=\”0\”></a>
Note that the \ allows the ” to show as part of the text to be added rather than being part of the code.
In this case you can substitute the html above with anything you like, but I am a variable “enquiryform” which is the URL of a page I have set elsewhere as a link and I am adding an icon rather than copy to link from.
It should be noted that this relies on each column being marked with a class. If this isn’t the case, you can probably add classes with jQuery before you run this step. You may even be able to modify this code to use the child number rather than looking for a class.