When I am deleting row from my table, also the table header is being deleted, how I can fix this?
$('#clubs tbody').on('click', '.deleteBtn', function() {
$(this).closest('tr').remove();
});
Button tag
<td>
<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"
title=#DbResHtml.T("Delete", "Resources")></button>
</td>
My button have a class of .delete so when I click it, my row is deleted together with my table header.
My table have and id of clubs while table body have and id of clubsTBody.
Table
<div class="table-responsive">
<table class="table table-striped my-4 " id="clubs">
<thead>
<tr>
<th>#DbResHtml.T("#", "Resources")</th>
<th>#DbResHtml.T("Клуб", "Resources")</th>
<th>#DbResHtml.T("Лига", "Resources")</th>
<th></th>
</tr>
</thead>
<tbody id="clubsTBody">
#foreach (var club in Model.Player.PlayerClubs)
{
<tr>
<td>#Html.DisplayFor(x => count)</td>
<td>#Html.DisplayFor(x => club.Club.Name)</td>
<td>#Html.DisplayFor(x => club.Club.League.LeagueType)</td>
<td>
<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"
title=#DbResHtml.T("Delete", "Resources")></button>
</td>
</tr>
count++;
}
</tbody>
</table>
</div>
Also I am adding dynamically rows into my table.
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length;i++) {
ids.push(cc[i]);
}
$.ajax({
type : "POST",
url : "#Url.Action("GetClubsById","Player")",
data : {"ids": ids},
success : function(data) {
console.log(data);
$('#clubs tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
$('.deleteBtn').on('click', function() {
$(this).closest('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
})
// /.../
})
The problem is here, when I am removing selected item from select list, without this code, everything is working perfectly but selected items doesn't get deselected.
$(`#select2-3 option:selected:contains("${value}")`)
.prop("selected", false)
.parent()
.trigger("change");
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length;i++){
ids.push(cc[i]);
}
$.ajax({
type: "POST",
url: "#Url.Action("GetClubsById","Player")",
data: {"ids": ids},
success: function(data) {
console.log(data);
$('#clubsTBody tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
$('.deleteBtn').on('click', function() {
$(this).closest('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
});
You nee to write this: $('#clubsTBody tr').remove(); instead of $('#clubs tr').remove();
You are removing all the TR in Ajax Response instead of Only Body TRs
I have a table that is programmatically added with an onclick event that calls a specific javascript function with the id of the row I want to edit. However it is not called. I have tried changing the button by adding a class and trying to get something there but it does not work. This used to work and I cannot figure out why or how to fix it.
function buildTable() {
$.ajax({
url: "getTable.php",
dataType: "json",
success: function(result) {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function (measurement) {
var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";;
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-outline-warning' onlick='editRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-pencil'></span></button> ";
message += "<button type='button' class='btn btn-outline-danger' onlick='removeRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-remove'></span></button></td></tr>";
$('#measurements').append(message);
});
}
}
});
}
The following is the HTML table it is being added to:
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
This is the edit function in question just in case I miss something with the argument signature:
function editRow(id) {
$.ajax({
url: "getMeasurement.php",
type: "post",
dataType: "json",
data: {
"id": id
},
success: function(data) {
if (data != null) {
data.forEach(function(result){
var id = result.id;
$('#editMeasurement').modal('show');
$('#editupper').val(result.upperBp);
$('#editlower').val(result.lowerBp);
$('#editwaist').val(result.waist);
$('#editweight').val(result.weight);
$('#editcomment').text(result.comment);
$('#editRowHidden').val(id);
});
}
}
});
}
I have tried changing the button by adding a class:
and trying to catch the event with $('.editRow').on("click", function() {} event with the same results.
You have a typo onlick instead of onclick.
Also, you could consider to use passive event listener as:
$(document).on("click", <target>,<your function>});
where <target> is the jquery selector for you button
and <your function> your callback.
This would increase readability and as well helps to keep the separation between HTML and JS. And also work for dynamically inserted targets.
Thanks to kmgt. If it was a snake it would have bit me. Have to use 'onclick' instead of 'onlick'.
First of all I agree with #dmitrii-g that you should use event-delegation to be able to handle any events on elements, that were added after DOM was rendered. (added dynamically). After that you should try to debug/print to console any information needed to ensure that you are passing correct values into your function. I've prepared sample example which will demonstrate this approach:
const result = [{
weigh_date: '01/01/2019',
weight: '200lbs',
id: 1,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
},
{
weigh_date: '01/01/2015',
weight: '100lbs',
id: 2,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
}
];
function buildTable() {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function(measurement) {
var message = "<tr><td>" + measurement.weigh_date + "</td>";
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-edit btn-outline-warning' id='" + measurement.id + "'>Edit</button> ";
message += "<button type='button' class='btn btn-delete btn-outline-danger' id='" + measurement.id + "'>Remove</button></td></tr>";
$('#measurements').append(message);
});
}
}
$('#measurements').on('click', '.btn-edit', function() {
const id = $(this).attr('id');
console.log('ID to be edited: ' + id);
// your stuff here
});
$('#measurements').on('click', '.btn-delete', function() {
const id = $(this).attr('id');
console.log('ID to be deleted: ' + id);
// your stuff here
});
buildTable();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
try this
$(document).on("click","tr",function() {
console.log(this,"click");
});
I'm very green when using jquery and AJAX. Not sure if AJAX would help in this situation. I've looked at this question its the closest to what i'm looking for.
Add new row to table using jQuery on enter key button
var inp = $("#txt");
// where #txt is the id of the textbox
$(".table-cell-text").keyup(function (event) {
if (event.keyCode == 13) {
if (inp.val().length > 0) {
$('#myTable tr:last').replaceWith('<tr class="table-row"><td class="table-cell">' + inp.val() + '</td>' +
'<td class="table-cell">' +
'<td></td>' +
'</td>' +
'<td class="table-cell">' +
'</td></tr>');
}
}
});
FIDDLE
I have a MySQL DB that I would like data retrieved from based off of the sku # entered into their respective rows. I have this working with a submit button using PHP, but this is for a project I have that uses a Barcode scanner.
There is a second part to this question but i'll try to figure that out on my own first before asking.
<?
if (!empty($_POST))
{
$db = new mysqli('localhost', 'root', 'password', 'table');
$result = $db->query('SELECT * FROM `users` ');
$result = $result->fetch_array();
print($result['id'].' - '.$result['username'] .' - '.$result['password']);
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<!-- head here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div><input id="txt" placeholder="Enter barcode" type="text"></div>
<table id="myTable">
<tr class="table-header">
<td class="table-cell">SKU</td>
<td class="table-cell">MODEL </td>
<td class="table-cell">DESCRIPTION</td>
<td class="table-cell">QTY</td>
</tr>
<tr class="table-row">
</tr>
</table>
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "test.php",
type: "post", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#myTable tr:last').replaceWith('<tr class="table-row"><td class="table-cell">' + inp.val() + '</td>' +
'<td class="table-cell">' + values[0] +
'<td> ' + values[1] + '</td>' +
'</td>' +
'<td class="table-cell">' + values[2] +
'</td></tr>');
}});
}
}
});
</script>
</body>
</body>
</html>
I tried with my dummy database with users and I get:
SKU MODEL DESCRIPTION QTY
40 1 Username 9z600248b669b62d75b300a07b89060n
I had limited success with the edited code. When I try to enter a different item # into the input field only the first value updates. Also, I'm trying to add a new row and retain the last row after entering a new value in the input field.
Here is the latest version of the script:
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "index.php",
type: "POST", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#report tr:last').replaceWith(
"<tr class='table-row'><td class=''>" + inp.val() + "</td>" +
"<td class=''>" + values[1] + "</td>" +
"<td class=''>" + values[2] + "</td>" +
"<td class=''>" + values[3] + "</td></tr>");
}});
}
}
}});
</script>
I did some more diggin around and I was able to resolve some of the issues I was having. However, I still can't get data from the DB when a new row is added.
Below is my code:
<div class="row">
<div class="col-md-1"></div>
<div class="col-xs-3">
<h3 class="h4 text-center"><input type="text" name="barcode" id="txt" size="90" class="col-md-9" value="" placeholder="Barcode / Product Name"></h3>
</div>
</div>
<br />
<div class="row">
<div class="col-md-1"><p class=""></p></div>
<div class="col-md-6">
<table id="report" class="table table-bordered table-hover">
<thead>
<tr>
<td>SKU</td>
<td>Model</td>
<td>Item Description</td>
<td>Qty</td>
</tr>
</thead>
<tbody>
<tr class='table-row'>
</tr>
</tbody>
</table>
</div>
</div>
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "index.php",
type: "POST", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#report tr:last').after(
"<tr class='table-row'><td class=''>" + inp.val() + " </td>" +
"<td class=''>" + values[1] + "</td>" +
"<td class=''>" + values[2] + "</td>" +
"<td class=''>" + values[3] + "</td></tr>");
}});
}
$('input[name=barcode]').val('');
}
});
</script>
I am trying to show data from 5 rows of Database (MySQL) to rows of table using on success of jQuery AJAX call. The data is in JSON format.
Issue: I am not able to figure out to get all of those rows. I can get only one row but console showed me all the rows in JSON format.
$.ajax({
url: '<?php echo base_url('ads/select_post'); ?>',
data: {},
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function (i, val) {
console.log(val.name);
$("#name").html(val.name);
$("#price").html(val.price);
$("#addr").html(val.addr);
$("#des").html(val.des);
$("#viewed").html(val.viewed);
$("#status").html(val.status);
});
}
});
Console output:
[{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasdf"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}]
HTML of the table i am sending data to,
<tbody id="items">
<tr>
<td>1</td>
<td><a><div id="name"></div> </a></td>
<td><a><div id="price"></div> </a></td>
<td><a><div id"addr"></div></a></td>
<td><div id="des"></div> </td>
<td><a><div id="viewed"></div></a></td>
<td><a><div id="status"></div></a></td>
</tr>
Please advise.
Lots of good answers, but since I've created an example I'll post that too. If nothing else it might give you, or someone else, an alternative solution. I'm using classes instead of Id's, and keep your original structure.
Since this was accepted as answer I should also mention why your code failed:
Your each loop is continually overwriting the contents of your table row data, instead of creating new rows. Another thing that needed fixing is that you had given the columns Id's, and those cannot stay (as they were) if you want to repeat the rows, since Id's within a page must be unique.
There are many methods to create new elements. I chose clone() as I figure you would always have a row for header that could easily be used to clone/copy. Also I added a unique Id attribute to each tr. These are not really used in the current implementation below, but it might be good to have as reference later in your project.
var data = [{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfas"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}];
//place within the Ajax success
$.each(data, function(i, val) {
var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (i + 1));
currRow.find('td:eq(0)').html(i + 1);
currRow.find('.name').html(val.name);
currRow.find('.price').html(val.price);
currRow.find('.addr').html(val.addr);
currRow.find('.des').html(val.des);
currRow.find('.viewed').html(val.viewed);
currRow.find('.status').html(val.status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody id="items">
<tr id="tr0">
<td>Id</td>
<td><a><div class="name">Name</div></a></td>
<td><a><div class="price">Price</div></a></td>
<td><a><div class="addr">Addr</div></a></td>
<td><div class="des">Des</div></td>
<td><a><div class="viewed">Viewed</div></a></td>
<td><a><div class="status">Status</div></a></td>
</tr>
</tbody>
</table>
You can try this, I test it locally and it works:
$.ajax({
url: '<?php echo base_url('ads/select_post'); ?>',
data: {},
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function (i, val) {
var tr = "<tr>" +
"<td>"+ (i + 1) + "</td>" +
"<td>"+ val.name + "</td>" +
"<td>"+ val.price + "</td>" +
"<td>"+ val.addr + "</td>" +
"<td>"+ val.des + "</td>" +
"<td>"+ val.viewed + "</td>" +
"<td>"+ val.status + "</td>" +
"</tr>";
$(tr).appendTo("tbody");
});
}
});
And your html table:
<table>
<tbody id="items">
</tbody>
</table>
You need something like this:
DEMO HERE
HTML Structure
<table>
<thead>
<th>Sl No.</th>
<th>Address</th>
<th>Description</th>
<th>Image</th>
<th>Name</th>
<th>Price</th>
<th>Status</th>
<th>Viewed</th>
</thead>
<tbody id="items">
</tbody>
</table>
JS
$.each(data, function (i, val) {
$("tbody#items").append("<tr><td>"+(i+1)+"</td><td><a><div>"+val.addr+"</div></a></td>"
+"<td><a><div>"+val.des+"</div></a></td>"
+"<td><a><div>"+val.img+"</div></a></td>"
+"<td><a><div>"+val.name+"</div></a></td>"
+"<td><a><div>"+val.price+"</div></a></td>"
+"<td><a><div>"+val.status+"</div></a></td>"
+"<td><a><div>"+val.viewed+"</div></a></td></tr>");
});
You need to create table rows() in the ajax success.
And you should not use same ids in the td tags.
var html = "";
$.ajax({
url: '<?php echo base_url('ads/select_post'); ?>',
data: {},
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function (i, val) {
console.log(val.name);
html +="<tr>";
html += "<td>" + val.name + "</td>" ;
html += "<td>" + val.price + "</td>" ;
html += "<td>" + val.addr + "</td>" ;
html += "<td>" + val.des + "</td>" ;
html += "<td>" + val.viewed + "</td>" ;
html += "<td>" + val.status + "</td>" ;
html +="</tr>";
});
$("$items").html(html);
}
});
Your html:
<table>
<tbody id="items">
</tbody>
</table>
You probably need some code like this, This is rough idea you can let me know if you don't get it
this.tableElement = jQuery('<table/>', {
}).appendTo(gridWrapElement);
var tableBody = jQuery('<tbody/>', {
'class': 'eg-table-body'
});
this.tableBodyRow = jQuery('<tr/>', {
});
var scope = this;
var columns = [{
name:"Name",
dataIndex:"name",
width: "33%"
},{
name:"Price",
dataIndex:"price",
width: "33%"
},{
name:"Address",
dataIndex:"addr",
width: "34%"
}];
$.each(this.columns, function(index, column) {
var tableBody = jQuery('<td/>', {
width: column.width,
columnDataIndex: column.dataIndex,
columnIndex: index
});
jQuery('<div/>', {
html: "<a>" + column.name + "</a>",
class: "eg-table-Body-div"
}).appendTo(tableBody);
tableBody.appendTo(scope.tableBodyRow);
scope.tableBodyItems.push(tableBody);
});
jQuery(this.tableBodyRow).appendTo(tableBody);
jQuery(tableBody).appendTo(this.tableElement);
var body = '';
$.each(val,function(i,j){
body = body + '<tr><td>'+i+1+'</td>';
body = body + '<td>'+j.name+'</td>';
body = body + '<td>'+j.price+'</td>';
body = body + '<td>'+j.addr+'</td>';
body = body + '<td>'+j.des+'</td>';
body = body + '<td>'+j.viewed+'</td>';
body = body + '<td>'+j.status+'</td></tr>';
});
$('#items').html(body);
This will give you the table with values
It is better if you can rows dynamically. Then append generated html into tbody table like example below :
HTML
<table>
<tbody id="items">
<tr>
<td>No.</td>
<td>name</td>
<td>price</td>
<td>addr</td>
<td>des</td>
<td>viewed</td>
<td>status</td>
</tr>
</tbody>
JS
var data = [{
"name": "dfasdfas",
"price": "0",
"addr": "dfasdfas",
"des": "sadfdfasdfasdf",
"viewed": "0",
"img": "",
"status": "1"
}, {
"name": "asdDasdA",
"price": "0",
"addr": "asdADasd",
"des": "ASDasdASD",
"viewed": "0",
"img": "",
"status": "1"
}];
/************ put this inside ajax success block*/
var output;
$.each(data, function (i, val) {
output += '<tr><td>' + i + '</td>' +
'<td><a><div id="name">' + val.name + '</div> </a></td>' +
'<td><a><div id="price">' + val.price + '</div> </a></td>' +
'<td><a><div id"addr">'+ val.addr +'</div></a></td>' +
'<td><div id="des">' + val.des + '</div> </td>' +
'<td><a><div id="viewed">' + val.viewed + '</div></a></td>' +
'<td><a><div id="status">'+
val.status+'</div></a></td></tr>';
});
$('#items').append(output);
/************ end */
DEMO
Try this. Its shows all data in table.
http://jsfiddle.net/Navneethk/zcpp51tc/2/
var html = '<tr>';
for(var i = 0 ;i < data.length;i++){
var val = data[i];
html += '<td>'+i+'</td>'+
'<td><a><div id="name'+id+'">'+ val.name +'</div> </a></td>'+
'<td><a><div id="price'+id+'">'+ val.price +'</div> </a></td>'+
'<td><a><div id"addr'+id+'">+ val.addr +</div></a></td>'+
'<td><div id="des'+id+'">' +val.des+ '</div> </td>'+
'<td><a><div id="viewed'+id+'">'+ val.viewed +'</div></a></td>'+
'<td><a><div id="status'+id+'">' val.status '</div></a></td>';
}
$("#items").html(html);
You were assigning all 5 data row to the same template so that you only see the last data set returned.
You should create those 5 row dynamically by using createElement or jQuery.