Not getting onclick event to fire from programmatically built table - javascript

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");
});

Related

Data showing undefined in table

I am trying to get my data into an HTML table. The JavaScript is properly detecting the data and is showing two rows in the table, which is correct. The issue is each of the fields of both rows display undefined. Not sure where to go from here.
$(function() {
var records = [];
$.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
$.each(data.records, function parseJSON(i, f) {
var tblRow = "<tr>" + "<td>" + f.company + "</td>" + "<td>" + f.companyDescription + "</td>" + "<td>" + f.role + "</td>" + "<td>" + f.roleDescription + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="wrapper">
<div class="profile">
<table id="userdata" border="2">
<thead>
<th>Company</th>
<th>Company Description</th>
<th>Role</th>
<th>Role Description</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
Again the table is showing two rows, which is correct, but each value of the rows says undefined.
You need to pull the fields key out of the record object:
$(function() {
var records = [];
$.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
$.each(data.records, function parseJSON(i, { fields: f }) {
var tblRow = "<tr>" + "<td>" + f.company + "</td>" + "<td>" + f.companyDescription + "</td>" + "<td>" + f.role + "</td>" + "<td>" + f.roleDescription + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="wrapper">
<div class="profile">
<table id="userdata" border="2">
<thead>
<th>Company</th>
<th>Company Description</th>
<th>Role</th>
<th>Role Description</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
I changed the second argument of the parseJSON function from f to { fields: f }; this uses object destructuring to grab the value of the fields entry in the object passed to the second argument and assigns it to the f variable so that the rest of the code can use that object to get their values.

How to append row(with mutiple input column and one dropdownlistcolumn) to table on ajax sucess

I need to add drop down or list box in place of comment from model added at view. kindly suggest any other alternative method since i am new to this
Html code:
#model Sampleapplication.Models.samplemodel
<body>
<table id="tabledetails" class="table table-bordered loaded-table">
<thead>
<tr>
<th> <p>Id</p></th>
<th> <p>Name</p></th>
<th> <p>Department</p></th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
on ajax success:
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd1'>" + item.Id + "</td>"
+ "<td class='prtoducttd2'>" + item.Name + "</td>"
+ "<td class='prtoducttd11'>#Html.ListBoxFor(m => m.sDepartmentList, Model.lstToDepartment, new { Name = "Departmentlst", id = "Departmentlst", #placeholder = "Select Deaprtment" })</td>"
+ "</tr>";
$('#tabledetails tbody').append(rows);

HTML/JS Table-Header does not match up to Table-Body

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

Copying Checked rows from one table to another table

Actually i am looking to copy the checked rows from the table of one div (table 1) to table of another div(table 2). But with the below script, when i check more than one checkbox, the first checked row is replaced by the lastly checked row. But i want like each checked row of table 1 should come in table 2 as one by one.
Any help appreciated. Thanks in advance!!!
HTML
<div class="form-group" id="jqcc" >
<table id="order-table" name="order-table">
<tr>
<th>Select</th>
<th>Medication</th>
<th>Max Issue Limit</th>
</tr>
<tbody></tbody>
</table>
</div>
Javascript
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab;
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
})
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
tab += "</tbody>"
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th> <th>Claim Amount</th> <th></th></tr></thead>" + tab + "</table>").show();
});
});
</script>
You try to change:
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab = "";
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th><th>Claim Amount</th> <th></th></tr></thead><tbody></tbody></table>").show();
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
//
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
// append row html to table with id
$("#peopleTable").append(tab);
})
});
});

How to send data from Json using Ajax in jquery for html element?

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.

Categories