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

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
. I've looked at quite a few 'solutions', but they are not helping. It's still adding the code twice (see screenshot below).


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;

As you can see I've tried using the
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 Source

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

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