MagicLegend MagicLegend - 9 days ago 5
Javascript Question

jQuery only execute .append once

I want to add an extra row with some extra calculations to an existing table. The table doesn't have a header tag, it's just figuring out what CSS to apply by itself. I'm adding an extra header via the code found below. Right now it's adding the header twice. The (edited) code of the table looks like this:

<!--This code is in a <form> with the id="train_form", hence the usage in the jQuery code-->
<table class="vis" style="width: 100%">
<tbody>
<tr>
<th style="width: 20%">Eenheid</th>
<th style="min-width: 400px">Behoefte</th>
<th>In het dorp/Totaal</th>
<th style="width: 120px">Rekruteren</th>
<th style="width: 80px">To Do:</th>
</tr>

<tr class="row_a">
<td class="nowrap">
<a href="#" class="unit_link" data-unit="spear">
<img src="image.png" style="vertical-align: middle" alt="" class="">
Speervechter
</a>
</td>
</tr>
<!-- There are 3 more entries here, but to not be too long I've removed them. They are not really necessary-->
<tr>
<td colspan="3">
</td>
<td>
<input class="btn btn-recruit" style="float: inherit" type="submit" value="Rekruteren" tabindex="11">
</td>
<th style="width: 80px">To Do:</th>
</tr>
</tbody>
</table>


The lines
<th style="width: 80px">To Do:</th>
are added by my script. The problem is that it also adds it to the last
<td>
. I've looked at quite a few 'solutions', but they are not helping. It's still adding the code twice (see screenshot below).

Example

The code that I'm using to add the lines:

$(function() {
var done = false;
if (!done) {
$("#train_form > .vis > tbody > tr:not(.row_a, .row_b)").one().append("<th style='width: 80px'>To Do:</th>");
done = true;
};
}).one();


As you can see I've tried using the
.one()
methods, and I've tried using a bool for it. Both don't work, since this code still gives the table seen in the image above.

Just to be clear, I have no control over the source, this is a script for an online browser game.

What am I doing wrong?

Answer

I think you want $.first() instead of $.one():

$("#train_form > .vis > thead > tr:not(.row_a, .row_b)")
    .first()
    .append("<th style='width: 80px'>To Do:</th>");
Comments