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
Related
I've a litte problem diplaying a table correctly.
The table-header ist not consistent with the table-body.
The table date gets displayed in the colums 1/3/5/7, so the odd columns are getting skipped, idk why this happens.
On the following link you can look how the table gets displayed.
Relevant Code:
HTML-Code:
<div id="accreqlist" hidden="true">
<h1>Accountanfragen Liste</h1>
<button class="btn btn-secondary btn-lm" id="accreqreturnbtn">zurück</button>
<form id="accreqlist_form">
<div id=accreq_message class="form__message form__message--error"></div>
</form>
<table class="tablelist" id="tblAccList">
<thead>
<tr>
<th>Accountanfrage ID</th>
<th>Name</th>
<th>E-Mail</th>
<th>Mobile</th>
<th>Action 1</th>
<th>Action 2</th>
</tr>
</thead>
<tbody>
<!--will get filled through js file-->
</tbody>
</table>
</div>
JS-Code:
function accountRequestlistclicked() {
$.getJSON("/api/accountRequests").done(handleAccountRequestlistReply);
}
function handleAccountRequestlistReply(reqs) {
$("#tblAccList tbody").empty();
for (let req of reqs) {
addReqToList(req);
}
}
function addReqToList(req) {
let id = req["accountRequestId"];
var newRow = "<tr>";
newRow += "<td>" + req["accountRequestId"] + "<td>";
newRow += "<td>" + req["accountRequestName"] + "<td>";
newRow += "<td>" + req["accountRequestEmail"] + "<td>";
newRow += "<td>" + req["accountRequestMobile"] + "<td>";
newRow +=
"<td> <button id = 'u" +
req["accountRequestId"] +
"' onClick='deleteAccRequest(" +
req["accountRequestId"] +
")'> Delete </button> </td>";
newRow +=
"<td> <button id = 'u" +
req["accountRequestId"] +
"' onClick='createUser(" +
req["accountRequestId"] +
")'> Account erstellen </button> </td>";
newRow += "</tr>";
$("#tblAccList tbody").append(newRow);
}
//accreq löschen
function deleteAccRequest(id) {
var urlstring = "/api/deleteAccountRequest/" + id;
$.ajax({
type: "DELETE",
url: urlstring,
success: deleteReqRespons,
dataType: "json",
contentType: "application/json",
});
}
//user erstellen
function createUser(id) {
var urlstring = "api/createUser/" + id;
$.ajax({
type: "Post",
url: urlstring,
success: createUserResponse,
dataType: "json",
contentType: "application/jsin",
});
}
Does somebody know how i can fix the table, so that the colums gets displayed correctly?
Im very thankful of every input!
Uff i know what was wrong. I forgot to close the td-tags. so for each data the </th> was missing :(( sorry for stealing your time, with this simple problem.
cheers
1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.
<table id="empTable">
<tr>
<th>Type</th>
<th>SimiScore</th>
<th>Rank</th>
<th>Introversion/Extraversion</th>
<th>Intuitive/Observant</th>
<th>Thinking/Feeling</th>
<th>Judging/Perceiving</th>
</tr>
{% for doc in docs %}
<tr>
<td>{{doc["type"]}}</td>
<td>{{doc["Simiscore"]}}</td>
<td>{{doc["Rank"]}}</td>
<td>{{doc["Introversion/Extraversion"]}}</td>
<td>{{doc["Intuitive/Observant"]}}</td>
<td>{{doc["Thinking/Feeling"]}}</td>
<td>{{doc["Judging/Perceiving"]}}</td>
</tr>
{% endfor %}
</table>
<p><input type="button" id="bt" value="Show Table Data" onclick="showTableData()" /></p>
<p id="info"></p>
2.This is my javascript code to display the data, but I'm unable to display it
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />'; // ADD A BREAK (TAG).
}
}
</script>
{
$(document).ready(function()
{
$.ajax({
url: "getjson.php",
type: "POST",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
}
this is an example you can use
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 have table rendered by js
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
Here is code
function GetCity() {
let citiesurl = '/cities/index';
$.ajax({
url: citiesurl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#cities").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info" onclick="DeleteCity()">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
}
})
}
I try to get value of cityId by button click.
Here is code
let id = $(this).closest('tr').find('.cityId').text();
But alert dhow me, that I get nothing.
Where is my error?
The problem is the context this which is not the clicked button.
Adopt the Event delegation approach for elements dynamically created:
$('#cities').on('click', 'button.btn', function() {...}
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).closest('tr').find('.cityId').text();
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
A better alternative is using the data-attributes
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button data-city-id="'+list[i].Id+'" type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).data('city-id');
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
You can modify you code the following way, using jquery:
$(document).ready(function() {
$('button').on('click', function() {
console.log($(this).data('city-id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- // these are your buttons. -->
<button data-city-id="2">Delete</button>
<button data-city-id="3">Delete</button>
<button data-city-id="4">Delete</button>
You can generate buttons something like:
'<button type="button" class="btn btn-info" data-city-id="' + list[i].Id + '">' + 'Удалить' + '</button>'
I am trying to get table value names with the following code:
my table :
function CreateBlockDeployTableRow(data) {
return "<tr>" +
"<td>" + data.EnvTypeName + "</td>" +
"<td>" + data.AppTypeName + "</td>" +
"<td>" + deleteBtn + "</td>" +
"</tr>";
}
my button:
var deleteBtn = '<button class="btn btn-danger unblock-button btn-sm
glyphicon glyphicon-minus" type=button > </button> '
on click function:
function UnblockRequestHandler()
{
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler();
});
}
and here I want to send my Environment and Application to server side and take the value of the rows in the table , but the code is not working and not taking anything:
function sendUnblockDeploySubmitHandler() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML +
'<br/>';
alert(values);
});
console.log(values);
}
html code :
<div class="tbl-responsive">
<table id="blockDeployTable" class="table table-hover
requestsblockDeployTable" style="font-size: 0.8em; margin-top: 120px;
text-align:center">
<thead>
<tr>
<th>Environment</th>
<th>Repo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Where am I wrong here I cannot understand?
You could just pass the click event through to the sendUnblockDeploySubmitHandler function:
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler(event); // pass event to function
});
function sendUnblockDeploySubmitHandler(event) {
var $row = $(event.target).closest('tr'); // event.target is the button
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
}
I've put together a jsbin to show this working: https://jsbin.com/sosimudubi/1/edit?html,js,console,output
You are trying to access jQuery(this) in the sendUnblockDeploySubmitHandler() method but the this handle does not refer to the button element. I would suggest you to directly pass the callback function when you bind the click event.
function UnblockRequestHandler() {
$('.unblock-button').click(sendUnblockDeploySubmitHandler);
}
This way, you can access the corresponding button element using jQuery(this) in the sendUnblockDeploySubmitHandler()