JinJinUK JinJinUK - 11 months ago 42
jQuery Question

Dynamically add table row when last row field clicked for the first time

I want to have a table which dynamically adds a row when the last row in the table is clicked. Specifically I have a row which have 2 text boxes and I would like to add a new row whenever a user clicks into either box.

The aim is to provide a growing list which would then have the option to delete rows etc. (but not specifically needed for this question!)

In my head the logic would work along the lines of

if (either text box clicked && is last row) then

Table fiddle here:

<table class="table table-sm table-hover table-condensed table-bordered" id="paramsTable">
<th class="text-center">key</th>
<th class="text-center">value</th>
<tr id="param01">
<td class="text-center">
<input class="vert-align" type="checkbox" value="">
<input class="form-control" id="paramKey01" type="text" aria-label="..." placeholder="key">
<input class="form-control" id="paramVal01" type="text" aria-label="..." placeholder="value">
<td class="text-center">
<button type="submit">Delete</button>

An example of this functionality is if anyone uses 'postman' and the headers tab when building a request!

Answer Source

Add below scripts and add class delete to the delete button.

 $(document).on('click','tr:last-child input',function(){