I'm developing an application for users management with spring mvc. I'm using this bootstrap table in my jsppage which make me do a research on the data in the table .
In my table the data of users is retreived from database . this is the code :
<div class="col-md-9">
<form action="#" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q"
placeholder="Search for" required> <span
class="input-group-btn">
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</form>
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${listUsers}" var="user">
<tbody>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.surname}</td>
<td>${user.email}</td>
<td>${user.contact}</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit"
data-toggle="modal"
onclick="location.href='<c:url value="/modifier/${user.id}" />'">
<span class="glyphicon glyphicon-pencil"></span>
</button>
</p>
</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="delete"
data-delete='${user.id}' data-toggle="modal"
data-target="#confirm-delete" data-href="/supprimer/${user.id}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</p>
</td>
</tr>
</tbody>
</c:forEach>
</table>
</div>
and this is the script which do the research on the table :
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
$('.search-sf').remove();
tableRowsClass
.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody
.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
} else {
$('.search-query-sf').remove();
}
if (rowText.indexOf(inputText) == -1) {
//hide rows
tableRowsClass.eq(i).hide();
} else {
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if (tableRowsClass.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
});
but when I've changed to dynamic table I have this result which make the word searching for : repeated n times !
I tried to change the code of the script but I failed to have the right script.
could some one help me please ?
It looks like this might be the problem
tableRowsClass.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>');
.each means that you're adding <tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr> to the start (because it's prepend) of your table, one for every element using .table-list-search tbody tr
try just moving tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>'); outside of the .each() so that it only runs once.
I echo Jamie's answer, but I'd do a bit more refactoring.
I would move the searching out into its own function and pass the required rows collection and search string into it.
I would also move the check for search text outside the each loop, because the value is available outside the loop and doesn't change.
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
var searchTable = function(rows, searchStr){
var searching = false;
rows.each(function(i, val){
var rowText = $(val).text().toLowerCase();
if (rowText.indexOf(searchStr) == -1) {
//hide rows
rows.eq(i).hide();
} else {
$('.search-sf').remove();
rows.eq(i).show();
}
if (rows.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
}
};
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
var inputText = $(that).val();
$('.search-sf').remove();
if (inputText != ''){
$('.search-query-sf').remove();
searchTable(tableRowsClass, inputText.toLowerCase())
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "' + inputText + '"</strong></td></tr>');
}
});
});
An alternative to using javascript to create the repeating table row could be to use the hidden attribute and use javascript to remove that attribute whenever the .keyup event fires. You can then use javascript to set the value of a span tag with the search query. I couldn't get this example to work on jsFiddle or plunker, but i made an example. (this is pure raw JS with no styling)
<head>
<script type="text/javascript">
function doSearch(){
document.getElementById("searchingForRow").removeAttribute("hidden");
document.getElementById("searching").innerHTML = document.getElementById("system-search").value
}
</script>
</head>
<body>
<div class="col-md-9">
<div class="input-group">
<form>
<div>
<input id="system-search" placeholder="Search for" >
<button type="submit" class="btn btn-default" onclick="doSearch()">
Search
</button>
</div>
</form>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tr class="search-query-sf" id="searchingForRow" hidden>
<td colspan="6"><strong>Searching for: <span id="searching"></span></strong></td>
</tr>
<tbody>
<tr>
<td>An Example data this does nothing</td>
</tr>
</tbody>
</table>
this example, when the search button is clicked, removed the hidden attribute, making that row visible, and set's the span in the row to the value of the textbox.
it's essentially what you are trying to do.
with this method, it doesn't matter how many times the code to remove the hidden attribute is called, nothing will render more than once.
Related
$(document).ready(function() {
$('.zk_btn').click(function(e) {
var pass_symbol= $('#' + lastid).val();
var split_id = lastid.split("_");
var nextindex = Number(split_id[1]) + 1;
$.ajax({
url:"record_count_3.php?pass_symbol=" + pass_symbol,
method:"POST",
success:function(data)
{
var json = JSON.parse(data);
var txt = '';
if(json.length > 0){
for(var i=0;i<json.length;i++){
txt = "<td>"+json[i].openrate+"</td><td>"+json[i].highrate+"</td><td>"+json[i].lowrate+"</td><td>"+json[i].closerate+"</td>";
$("#example > tbody > tr").append(txt);
}
$('#example > tbody').append('<tr class="txt_ '+ nextindex +'"><td><input type="text" id="txt_'+ nextindex +'" name="symbol" class="txtfield" /></td></tr> </tbody>');
}
$('.content').html(data);
}
})
});
});
I have a problem iam fetching data from ajax call and move in json varibale.when write symbol in input box and fetching records and display in 1st td,and append in new row. and another insert symbol and click submit button fetching the record and display in second td but problem second record display in first row and second row just like screen shot. mcb records display in 2nd row not in 1st row. please suggest my mistake
<table id='example' border='1' cellspacing='1' cellpadding='1' style='width:900px;' >
<thead>
<th> Marksymbol</th>
<th class='namecol '> Openrate</th>
<th class='namecol'> Highrate</th>
<th class='namecol'> Lowrate</th>
<th class='namecol'> Closerate</th>
</tr>
</thead>
<tbody>
<tr class ='txt_1'>
<td > <input type='text' name="symbol" id='txt_1' class='txtfield'/>
</td>
</tr>
</table>
<input type="button" id= "btnclick" class="zk_btn zk_btn_submit" name="submit1" value="SUBMIT"/>
It's working now
$('#example tr:last').closest('tr').append(txt);
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();
} );
I'm trying to remove row from my dynamic table. I've success to .append new row from JavaScript.
JavaScript
$(document).ready(function() {
// table #pos add-row
$(".add-row").keypress(function(e) {
if (e.which == 13) {
var barcode = $("#barcode").val();
$.ajax({
type: "post",
url: "production/ajax/load.php",
dataType: "json",
data: {
barcode: $("#barcode").val()
},
success: function(data) {
$("#pos tbody").append(data['content']);
}
});
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
alert('Success');
$("#pos tbody tr").remove();
});
})
load.php
<?php
if (isset($_POST['barcode'])) {
require '../controller/connection/connection-management.php';
$barcode = $_POST['barcode'];
$status = false;
$sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
while($row = mysqli_fetch_assoc($result)) {
$barcode = $row['code'];
$title = $row['title'];
$sellingPrice = number_format($row['selling_price'], 0, ',', '.');
$quantity = 1;
$discount = $row['discount'];
$total = number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');
$append = "<tr class='pointer'>
<td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
<td><small>{$barcode}</small></td>
<td><div style='text-align: justify'><strong>{$title}</strong></div></td>
<td align='right'>{$sellingPrice}</td>
<td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
<td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
<td align='right'>{$total}</td></td>
</tr>";
}
$status = true;
}
$data = array(
"status" => $status,
"content" => $append
);
echo json_encode($data);
}
?>
pos.php it's html table
<div class="x_title">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
</span>
<input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>Receive</li>
<li>Return</li>
<li>Purchase Order</li>
<li>Transfer</li>
<li>Store Account Payment</li>
</ul>
</div>
</div>
</div>
<div class="x_content">
<div class="table-responsive">
<table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
<th style="text-align:right" class="column-title col-sm-1">Cost </th>
<th style="text-align:center" class="column-title col-sm-2">Qty. </th>
<th style="text-align:center" class="column-title col-sm-1">Disc % </th>
<th class="column-title col-sm-1" style="text-align:right">Total </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
So when I add new row in the table, everything works fine like this picture:
But when I click trash icon with class='delete-row', that's is not working. So I think, when I append data to table tbody it's not read class or id from the new row.
Please someone help. I can't find any similar questions like mine. I just want to know, how to remove table row when I click trash icon from JavaScript.
You have two issues here (which is why I have not voted to close as a duplicate). Firstly you need to use a delegated event handler on the .delete-row element as it is appended to the DOM after load. Your current code does nothing as you attempt to attach the event handler before the element exists.
Secondly, you need to use DOM traversal to remove only the parent tr of the clicked button. At the moment your code would remove all rows. Try this:
$('#pos').on('click', '.delete-row', function() {
$(this).closest('tr').remove();
});
Did you tried delegate?
$(document).delegate('.delete-row', 'click', function(){
//your remove code here
});
You can also use on (for jquery versions 1.7.1+)
$(document).on('click', '.delete-row', function(){
//your remove code here
});
Below JSFiddle link is that of a working form, where submitted form values from dynamic rows gets saved to a mysql table using ajax without any page refresh. The outcome of the form submission (i.e Success or Error) will be shown in a div which has an id 'results' using javascript.
JSFiddle Demo
Form Markup
<form name="names" id="names" method="post" action="">
<div class="container">
<div class="table-responsive">
<button type="button" class="btn btn-success addmore">Add</button>
<button type="button" class="btn btn-danger delete">Remove</button>
<br />
<table id="demo" class="table table-bordered table-condensed table-striped table-hover">
<thead>
<tr>
<th>
<input class="check_all" type="checkbox" onclick="select_all()" />
</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="case" />
</td>
<td>
<input class="form-control" type="text" name="fname[]" id="fname_1" required>
</td>
<td>
<input class="form-control" type="text" name="lname[]" id="lname_1" required>
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div id="results"></div>
<div id="results2"></div>
</div>
<!-- ./table-responsive -->
</div>
Javascript for Add/Remove Table Rows, Checkbox Row(s) Selection
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
check();
});
var i = $('table tr').length;
$(".addmore").on('click', function() {
count = $('table tr').length;
var data = "<tr><td><input type='checkbox' class='case'/></td>";
data += "<td><input class='form-control' id='fname_" + i + "' name='fname[]' required/></td>";
data += "<td><input class='form-control' id='lname_" + i + "' name='lname[]' required/></td></tr>";
//alert(data);
$('table').append(data);
row = i;
i++;
});
function select_all() {
$('input[class=case]:checkbox').each(function() {
if ($('input[class=check_all]:checkbox:checked').length == 0) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
var selected = $('#' + id).html(key + 1);
});
}
Javascript for Form Submission using Ajax
// form submission through ajax
$(document).ready(function() {
$(function() {
$("#names").on("submit", function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: "savename.php",
data: $(this).serialize(),
success: function(response) {
if (response == "Name creation successfull.") {
$("#results").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
} else {
$("#results2").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
}
//timing the alert box to close after 5 seconds
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 2000);
//Adding a click event to the 'x' button to close immediately
$('.alert .close').on("click", function(e) {
$(this).parent().fadeTo(500, 0).slideUp(500);
});
$('#names')[0].reset();
},
error: function(response) {
alert(response);
}
});
});
});
});
What I like to implement is this,
User first selects the rows which he/she wants to insert into the mysql table by selecting the checkbox at the beginning of each row.
After selecting the rows, upon clicking the submit button only those selected row values should be inserted into the mysql table.
Tried to implement this by trying out the solutions from various posts similar to this one on this site but was not successful.
Used the solution provided by the user skobaljic (Thank you very much) in this stackoverflow post. Using this code now am able to post only those form values which are from the selected rows to a mysql table.
Updated JSFiddle Working Demo
Following line is for debugging purpose only, comment out after you are done.
$('.submit_data').text(toPost);
While the code works and gets the job done, am just a novice when it comes to javascript, so need expert opinion to mark this post as solved.
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/