ray dauodi ray dauodi - 4 months ago 8
jQuery Question

JavaScript code outputs twice when clicking submit button

For some reason, the code in the example below keeps outputting twice when clicking the button and I can’t figure out the cause.



var onClick = function() {
var cars = ["Saab", "Volvo", "BMW"];
var rows = "";
rows += "<tr><td> " + cars[0] + " </td></tr>";
$(rows).appendTo("#list tbody");
};

$('#button').click(onClick);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<table id="list" class="table table-bordered; sortable">
<thread>
<tr>
<th>Group Name</th>
</tr>
</thread>
<tbody></tbody>
</table>





JSFiddle.

Answer

That’s because you have a typo: <thread> should be <thead>.

This typo caused your table structure to be invalid, making the browser attempt to correct it to this:

<thread></thread>
<table id="list" class="table table-bordered; sortable">
  <tbody>
    <tr>
      <th>Group Name</th>
    </tr>
  </tbody>
  <tbody></tbody>
</table>

Thereby, your <table> had two <tbody> elements, making the "#list tbody" selector yielding two results, thus appending it twice.

Comments