How Can I Pull Dynamically Created Input Fields from jQuery/JavaScript - javascript

I am having trouble pulling information from dynamically created text fields within a container from bootstrap. For what I have for "Dropoff Locations", I need to be able to store the information of an address into one address, and then each full address into an array of addresses. I am unsure of how to do this, especially using jQuery.
<!-- Dropoff Locations -->
<div class=" mb-4">
<div class="card border-0 shadow">
<div class="card-body text-center">
<h5 class="card-title mb-0">Drop-Off Location(s)</h5>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead>
<tr>
<th class="text-center">
Street Address
</th>
<th class="text-center">
City
</th>
<th class="text-center">
State
</th>
</tr>
</thead>
<tbody>
<tr id='addr0' data-id="0" class="hidden">
<td data-name="name">
<input type="text" name='name0' placeholder='Street Address' class="form-control"/>
</td>
<td data-name="mail">
<input type="text" name='mail0' placeholder='City' class="form-control"/>
</td>
<td data-name="desc">
<input type="text" name="desc0" placeholder="State" class="form-control"/>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-primary float-right text-white">Add Stop</a>
This is the script code
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr"+newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(0) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add delete button and td
/*
$("<td></td>").append(
$("<button class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>")
.click(function() {
$(this).closest("tr").remove();
})
).appendTo($(tr));
*/
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
if any help can be given that would be great!

You can add an object "addresses" to store all of your addresses, and then on a "change" event of an input field, get the row id and name of the field being changed, and then add it to the addresses object.
I added a basic example to your code, minus the sorting which was throwing a different error. Run the code snippet to see how it works.
$(document).ready(function() {
var addresses = {};
$(document).on('change', '#tab_logic input', function () {
var rowid = $(this).parents('tr').attr('id');
var name = $(this).attr('name');
// Initialize address row if it hasn't been created yet.
if (!addresses[rowid]) addresses[rowid] = {};
// Add or update this field.
addresses[rowid][name] = $(this).val();
console.log(addresses);
});
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
console.log(newid);
var tr = $("<tr></tr>", {
id: "addr"+newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(0) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
});
});
$("#add_row").trigger("click");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Dropoff Locations -->
<div class=" mb-4">
<div class="card border-0 shadow">
<div class="card-body text-center">
<h5 class="card-title mb-0">Drop-Off Location(s)</h5>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead>
<tr>
<th class="text-center">
Street Address
</th>
<th class="text-center">
City
</th>
<th class="text-center">
State
</th>
</tr>
</thead>
<tbody>
<tr id='addr0' data-id="0" class="hidden">
<td data-name="name">
<input type="text" name='name0' placeholder='Street Address' class="form-control"/>
</td>
<td data-name="mail">
<input type="text" name='mail0' placeholder='City' class="form-control"/>
</td>
<td data-name="desc">
<input type="text" name="desc0" placeholder="State" class="form-control"/>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-primary float-right text-white">Add Stop</a>

Related

How to read data into an array from a dynamic table AND validate data when added more rows

I am just starting to program with javascript and I ran into this difficulty:
I created a dynamic table in html and javascript. I have already created the function to add rows and delete.
But I am having some difficulty in saving the received data into the array. It only saves the first row into the array. I want it to loop and save all the respective data in the array.
type here
My html code:
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr id="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata1[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata2[]" id="val_2"placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata3[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar
</button>
</div>
</div>
My Javascript code:
function arraySaveData() {
var data = [];
//var dataMain = [];
//for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function () {
data.push({
verticePolig: $('input[name="namesavedata1[]"]').val(),
});
data.push({
coordM: $('input[name="namesavedata2[]"]').val(),
});
data.push({
coordP: $('input[name="namesavedata3[]"]').val(),
});
});
console.log(data);
//dataMain.push(data);
//}
//console.log(dataMain);
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata1[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata2[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata3[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
The problem is in the loop you have to add the data. You always take the same 3 inputs in each loop.
You should receive the current element in the callback function for each loop it makes, something like the example below:
$('#mytableform1').each(function (_, element) {
// element is the current row <tr id="allDataRow">
// now you find children element value
const verticePolig = $(element).find('namesavedata1[]').val()
const coordM = $(element).find('namesavedata2[]').val()
const coordP = $(element).find('namesavedata3[]').val()
data.push({
verticePolig,
coordM,
coordP
})
});

Calculate the row date depending on previous row in the table

I have this dynamic table. Add more button append a new row. Row consists of number or days and date field. Means how many days added results in date.
Now in the second row, if I add a number of days; it must check the previous previous row date or number and result the date. But rowSelected.prev('tr')[0] gives me no value.
Can anybody please help me.
$(function() {
$("#add-more").click(function() {
$("#main-table").each(function() {
let tds = '<tr>';
jQuery.each($('tr:last td', this), function() {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$(document).on('change', '.total-days', function(e) {
let rowSelected = $(this).closest('tr');
const someDate = new Date();
someDate.setDate(someDate.getDate() + parseInt($(this).val()));
const newDate = someDate.toISOString().substr(0, 10);
rowSelected.find('.expected-delivery-date').val(newDate);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-sm-6 right">
<a class="inline btn btn-primary" id="add-more">Add More</a>
</div>
<table class="table table-bordered" id="main-table" border="1">
<thead>
<tr>
<th>No.</th>
<th>From</td>
<th>Expected Delivery Date</td>
</tr>
</thead>
<tbody id="rows">
<tr>
<td><input class="form-control" type="text" name="deliverableNumber[]" /></td>
<td><input class="form-control total-days" type="number" value="1" name="deliverableNumberOfDays[]" /></td>
<td>
<input class="form-control expected-delivery-date" type="date" name="deliverableExpectedDeliveryDate[]" />
</td>
<td><i class="fa-2x fa fa-trash" onclick="SomeDeleteRowFunction(this)" title="Remove row"></i></td>
</tr>
</tbody>
</table>

How can I validate dynamically added dependent calendar fields

I've a form on my website where I'm getting multiple event details from my customers. They can share event details and event date.
I want to let them able to add multiple events with details but dynamically. Currently I wrote JavaScript for this and it's working fine.
Now, what I want is each time the value for next date should be grater than the previous one. So If they added 2 events suppose, the date for the second event should be based on date for first event and should be greater and same is true for upcoming dates.
How can I do that?
var tableCount = 1;
var index = 1;
$(document).on('click', 'button.add_time', function(e) {
e.preventDefault();
tableCount++;
$('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');
$('#timeTable' + tableCount).find("input").val("");
index++;
$('#timeTable' + tableCount + ' .aa').html(tableCount);
});
$(document).on('click', 'button.removeTime', function() {
var closestTable = $(this).closest('table');
if (closestTable.attr('id') != "timeTable") {
closestTable.remove();
}
tableCount--;
if (tableCount < 1) {
tableCount = 1;
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table" class="form-group">
<table id="timeTable" class="tg">
<tr class="form-group">
<td class="aa">1</td>
<td class="tg-yw4">
<button class="btn form-control btn-danger removeTime">Remove Events</button>
</td>
<td class="col-sm-4">
<input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">
</td>
</tr>
<tr>
<td class="aa">1</td>
<td class="tg-yw4">Event Description:</td>
<td>
​<input name="event_descriptions[]" type="text" placeholder="Event description:" />
</td>
</tr>
</table>
</div>
<div class="my-5">
<button class="add_time btn btn-info">Add More Events</button>
</div>
Whenever user inputs the date in input box you can check if the date which he/she has enter is less then previous date by looping through all previous dates inputs using each loop and depending on this show some error message.
Demo Code :
var tableCount = 1;
var index = 1;
//on input of date
$(document).on('input', 'input[name*=events]', function(e) {
//get that date
var edate = new Date($(this).val());
var $this = $(this).siblings("span.error");
$this.text("")//empty previous error if any
//loop through dates inputs
$("input[name*=events]").each(function() {
if ($(this).val() != null) {
//get input value
var sdate = new Date($(this).val())
//check user input is less then previous date
if (edate < sdate) {
console.log("date is less then previous date");
$this.text("date is less then previous date")//show eror
}
}
})
});
$(document).on('click', 'button.add_time', function(e) {
e.preventDefault();
tableCount++;
$('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');
$('#timeTable' + tableCount).find("input").val("");
index++;
$('#timeTable' + tableCount + ' .aa').html(tableCount);
});
$(document).on('click', 'button.removeTime', function() {
var closestTable = $(this).closest('table');
if (closestTable.attr('id') != "timeTable") {
closestTable.remove();
}
tableCount--;
if (tableCount < 1) {
tableCount = 1;
}
return false;
});
.error {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table" class="form-group">
<table id="timeTable" class="tg">
<tr class="form-group">
<td class="aa">1</td>
<td class="tg-yw4">
<button class="btn form-control btn-danger removeTime">Remove Events</button>
</td>
<td class="col-sm-4">
<!--added this to show error -->
<span class="error"></span>
<input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">
</td>
</tr>
<tr>
<td class="aa">1</td>
<td class="tg-yw4">Event Description:</td>
<td>
​<input name="event_descriptions[]" type="text" placeholder="Event description:" />
</td>
</tr>
</table>
</div>
<div class="my-5">
<button class="add_time btn btn-info">Add More Events</button>
</div>

Multiple Table Filters

I want to filter more than once in this table at the same time. It happens when I enter the $table.find('tbody tr:visible'); code, but it gets corrupted when I use the backspace in the filtering part because it only searches within the visible TR. (Original: $table.find('tbody tr');)
How can I solve this problem?
$(document).ready(function() {
$('.filterable .btn-filter').click(function() {
var $panel = $(this).parents('.filterable'),
$filters = $panel.find('.filters input'),
$tbody = $panel.find('.table tbody');
if ($filters.prop('disabled') == true) {
$filters.prop('disabled', false);
$filters.first().focus();
} else {
$filters.val('').prop('disabled', true);
$tbody.find('.no-result').remove();
$tbody.find('tr').show();
}
});
$('.filterable .filters input').keyup(function(e) {
/* Ignore tab key */
var code = e.keyCode || e.which;
if (code == '9') return;
/* Useful DOM data and selectors */
var $input = $(this),
inputContent = $input.val().toLowerCase(),
$panel = $input.parents('.filterable'),
column = $panel.find('.filters th').index($input.parents('th')),
$table = $panel.find('.table'),
$rows = $table.find('tbody tr');
/* Dirtiest filter function ever ;) */
var $filteredRows = $rows.filter(function() {
var value = $(this).find('td').eq(column).text().toLowerCase();
return value.indexOf(inputContent) === -1;
});
/* Clean previous no-result if exist */
$table.find('tbody .no-result').remove();
/* Show all rows, hide filtered ones (never do that outside of a demo ! xD) */
$rows.show();
$filteredRows.hide();
/* Prepend no-result row if all rows are filtered */
if ($filteredRows.length === $rows.length) {
$table.find('tbody').prepend($('<tr class="no-result text-center"><td colspan="' + $table.find('.filters th').length + '">No result found</td></tr>'));
}
});
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container">
<h3>The columns titles are merged with the filters inputs thanks to the placeholders attributes</h3>
<hr>
<p>Inspired by this snippet</p>
<div class="row">
<div class="panel panel-primary filterable">
<div class="panel-heading">
<h3 class="panel-title">Users</h3>
<div class="pull-right">
<button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button>
</div>
</div>
<table class="table">
<thead>
<tr class="filters">
<th><input type="text" class="form-control" placeholder="#" disabled></th>
<th><input type="text" class="form-control" placeholder="First Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Last Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Username" disabled></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Markos</td>
<td>Ottoass</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacobos</td>
<td>Thorntonass</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
https://jsfiddle.net/b0vj6p4n/
jquery.Datatables could be used, it has various features related to searching, sorting and loading data.
The site has quite a few examples to get started with loading data and setting up a table:
https://datatables.net/examples/basic_init/zero_configuration.html
The following snippet could be used to configure a table as datatable:
$(document).ready(function() {
$('#example').DataTable();
} );

Duplicating table rows with clone

I am having an issue I am struggling to resolve. I have two tables
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table1">
<thead>
<tr>
<th>Campaign Type</th>
<th>Deployment Date</th>
<th>Additional Information</th>
</tr>
</thead>
<tbody>
<tr class='template'>
<td>
<select class="selectType" name='typeInput[0][campType]' id="campInput">
<option value=""></option>
<option value="Main">Main</option>
<option value="Other">Standalone</option>
</select>
</td>
<td>
<input type="text" name='typeInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
<td>
<textarea name='typeInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
</tr>
</tbody>
</table>
<a id='add' class="pull-right btn btn-default">Add Row</a>
<a id='delete' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin alignment" id="table4">
<thead>
<tr>
<th>Additional Information</th>
<th>Deployment Date</th>
</tr>
</thead>
<tbody>
<tr class='template4'>
<td>
<textarea name='amendsInput[0][addInfo]' id="additionalInput" placeholder='Additional Information' class="form-control noresize"></textarea>
</td>
<td>
<input type="text" name='amendsInput[0][deliveryDate]' id="dateInput" placeholder='Deployment Date' class="form-control dateControl"/>
</td>
</tr>
</tbody>
</table>
<a id='add4' class="pull-right btn btn-default">Add Row</a>
<a id='delete4' class="pull-right btn btn-default">Delete Row</a>
</div>
</div>
</div>
</div>
One table has 3 inputs, the other has 2. When the add button is pushed on either table, I am cloning the table row, which includes cloning a datepicker.
Things have been going fine but now I have a problem. The second table I end everything with 4 e.g. table4, template4, add4 and delete4. I then duplicated the Javascript from the preious table but added 4 to everything (I duplicated it because this table has different inputs). This resulted in the following code.
$(function() {
initJQueryPlugins();
$('#add').on('click', function() {
$last_row = $('#table1 > tbody > tr').last();
if(!hasValues($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row($('#table1'));
}
});
$('#delete').on('click', function() { delete_row($('#table1')); });
$('#add4').on('click', function() {
$last_row = $('#table4 > tbody > tr').last();
if(!hasValues4($last_row)){
alert('You need to insert at least one value in last row before adding');
} else {
add_row4($('#table4'));
}
});
$('#delete4').on('click', function() { delete_row4($('#table4')); });
});
function add_row($table) {
var tr_id = $table.find('tr').length - 1;
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".selectType", $tr).select2({
tags: true
});
}
function hasValues($row){
$optVal = $row.find('td option:selected').text();
$inputVal = $row.find('td input').val();
$textVal = $row.find('td textarea').val();
if($optVal != "" || $inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row($table) {
var curRowIdx = $table.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function add_row4($table4) {
var tr_id = $table4.find('tr').length - 1;
var $template = $table4.find('tr.template4');
var $tr = $template.clone().removeClass('template4').prop('id', tr_id);
$tr.find(':input').each(function() {
if($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker').removeData('datepicker');
}
var input_id = $(this).prop('id');
input_id = input_id + tr_id;
$(this).prop('id', input_id);
var new_name = $(this).prop('name');
new_name = new_name.replace('[0]', '['+ tr_id +']');
$(this).prop('name', new_name);
$(this).prop('value', '');
});
$table4.find('tbody').append($tr);
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
}
function hasValues4($row4){
$inputVal = $row4.find('td input').val();
$textVal = $row4.find('td textarea').val();
if($inputVal != "" || $textVal != ""){
return true;
} else {
return false;
}
}
function delete_row4($table4) {
var curRowIdx = $table4.find('tr').length - 1;
if (curRowIdx > 2) {
$("#" + (curRowIdx - 1)).remove();
curRowIdx--;
}
}
function initJQueryPlugins() {
add_row($('#table1'));
add_row4($('#table4'));
}
I have set up a working FIDDLE
The problem is this. If you start adding a few rows in the first table, this all works fine. After this, add a few rows in the second table. This seems to work fine. However, now start deleting rows in the second table. For some reason it seems to also delete rows in the first table.
So my main question is why does this happen? Additionally, is there any way I can do this without duplicating the code? The second table does not use select2.
Thanks
You are deleting this:
$("#" + (curRowIdx - 1)).remove();
This id is also available in the first table, you have to choose a more specified selector
like:
$table4.find("#" + (curRowIdx - 1)).remove();
or better: (comment from K. Bastian above)
$table4.find('tr').last().remove()
I edited your sample here:
https://jsfiddle.net/cLssk6bv/
Here I also deleted the dublicated code, only the different insert method still exist:
https://jsfiddle.net/cLssk6bv/1/

Categories