jpmyob jpmyob - 20 days ago 6
jQuery Question

Jquery insert row with ajax not putting row in correct order

(Due to me not being able to answer some basic questions about 'values' - I have re-worded the objective - to hopefully make getting to the solution easier/clearer)

This HTML is a starting point. When I click on the 'button' of a row, I want to insert a row AFTER that row. The contents of that new row will come from an ajax call, but for THIS question I just need to insert "tom, dick or harry" (depending on what was selected...) in a TR after.

<table id="xTable" >

<thead>
...
</thead>

<tfoot>
...
</tfoot>

<tbody>

<tr>
<td nowrap class="segment" >
<div class="btn-group" >
<button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > + <span class="caret" ></span></button>
<ul class="dropdown-menu segmentList" >
<option onclick="insRow('tom')" >tom</option>
<option onclick="insRow('dick')" >dick</option>
<option onclick="insRow('harry')" >harry</option>
</ul>
</div>
<span class="segmentLabel" >BOB</span>
</td>
</tr>


<tr>
<td nowrap class="segment" >
<div class="btn-group" >
<button class="btn btn-default btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > + <span class="caret" ></span></button>
<ul class="dropdown-menu segmentList" >
<option onclick="insRow('tom')" >tom</option>
<option onclick="insRow('dick')" >dick</option>
<option onclick="insRow('harry')" >harry</option>
</ul>
</div>
<span class="segmentLabel" >LISA</span>
</td>
</tr>

</tbody>

</table>


Here is the JS I have now - that doesn't work

function insRow( i ) {

var tr = $( this ).parents().closest( 'tr' );
$( '#xTable tbody' ).append( '<tr><td>' + i + </td></tr>' ).insertAfter( tr );

};


Here's a fiddle...
https://jsfiddle.net/w95xsd2L/3/

Answer

See Fiddle: https://jsfiddle.net/w95xsd2L/4/

  1. There is a lot going wrong in your setup, one problem is passing along this which could be avoided by explicitly supplying it when you call the function via insRow.call(this, ...).

  2. Then there's the manner in how you refer to parents().closest(), where parents() isn't necessary.

  3. You also don't need the insertAfter or to do another table lookup, simply apply after() to the already found TR, you found with closest

JS:

function insRow( i ) {

    var $tr = $( this ).closest( 'tr' );
    $tr.after( '<tr><td>' + i + '</td></tr>' );

};