JSFiddle - React, Tailwind, and code Playground
HTML
<form>
Number to start increment from:
<input id="increment_num" name="increment_num" placeholder="" type="text" value="5" /></br>
Values:
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody id="input_table">
<tr id="pq_entry_1">
<td><input type="text" id="increment_id_1" name="increment_id_1" readonly value="5" /></td>
<td><input type="text" name="first_name" placeholder="First Name" /></td>
<td><input type="text" name="last_name" placeholder="Last Name" /></td>
</tr>
</tbody>
</table>
<input type='button' id='btnAdd' value='add text box' />
<input type='button' id='btnDel' value='Delete' /></br>
</form>
JavaScript
$(document).ready(function () {
//var num = $('.clonedSection').length;
var $increment_num = $('#increment_num');
var interval = 3000; //3000 = 3 seconds
function doAjax() {
$.ajax({
type: 'POST',
url: 'personAutoIncrement.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
var $cloned = $('#input_table tr');
var num = parseInt(data);
$increment_num.val(num);
$cloned.each(function(i){
$(this).find('input').first().val(base_number+i);
})
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
// this should be removed
var base_number = 1 + Math.floor(Math.random() * 6);
var $cloned = $('#input_table tr');
$increment_num.val(base_number);
$cloned.each(function(i){
$(this).find('input').first().val(base_number+i);
})
}
});
}
setTimeout(doAjax, interval);
$('#btnAdd').click(function () {
var $clones = $('#input_table tr'),
num = $clones.size() + 1,
next_num = parseInt($clones.last().find('input[name^="increment_id"]').val()) + 1,
$template = $clones.first(),
newSection = $template.clone().attr('id', 'pq_entry_'+num),
ident = 'increment_id_'+num;
// clear out all sections of new input
newSection.find('input').not('[name^="increment_id"]').val('');
newSection.find('input[name^="increment_id"]').attr({
'id': ident,
'name': ident
}).val(next_num);
$('#input_table').append(newSection);
if (num == 5) $('#btnAdd').prop('disabled', 'disabled');
});
$('#btnDel').click(function () {
var num = $('.clonedSection').length; // how many duplicate input fields we currently have
$('#pq_entry_' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').prop('disabled', '');
// if only one element remains, disable the "remove" button
if (num - 1 == 1) $('#btnDel').prop('disabled',...