I've a table which is dynamically generated. In its row, I'm placing buttons.
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test()'></td>";
tr = tr + "</tr>";
};
On a button click, I'd like to get the particular cell value of that row. E.g.: If I click on the age in the first row, then the value I have to get is 50. And if I click on the button in second row, then I should get 94.
How can I get the table cell value on a button click?
Here is your solution for dynamic table:
<script language="javascript">
var tbl = document.getElementById("tblId");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
</script>
So, By using this javascript you can get value of any table cell.
You can pass age to button onclick function like onclick='test('"+resp[i].age +"')'
for (var i = 0; i < resp.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td >" + resp[i].Date + "</td>";
tr = tr + "<td >" + resp[i].age + "</td>";
tr = tr + "<td >" + resp[i].Hour + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test("+resp[i].age +")'></td>";
tr = tr + "</tr>";
};
Here is your solution:
$(document).find('.theButton').on('click',function(){
var age = $(this).parents('tr:first').find('td:eq(1)').text();
console.log(age);
});
Try this example with jQuery, I have replaced your function test, with rowid
https://jsfiddle.net/ucostea/2thyj0ft/
$(document).on("click", ".theButton", function(){
alert("Aage: "+$('.age_'+$(this).attr('rownr')+'').text());
});
for (var i = 0; i < 10; i++) {
var tr = "";
tr = tr + "<tr >";
tr = tr + "<td class='date_"+i+"'>Date" + i + "</td>";
tr = tr + "<td class='age_"+i+"'>Age " + i + "</td>";
tr = tr + "<td class='hour_"+i+"'>Hour " + i + "</td>";
tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' rownr='" + i + "'></td>";
tr = tr + "</tr>";
$('.table tbody').append(tr);
};
Related
So I'm trying to get the value of the USUARIO column when I'm pressing the button of its same row:
For example, if I was about to press the first button, it should give me 3 as a result
In my code I have this:
function(response) {
var t = "";
var tr = "";
tr += "<thead>";
tr += "<th>USUARIO</th>";
tr += "<th>FECHA INICIO</th>";
tr += "<th>FECHA FIN</th>";
tr += "<th>TIPO EMERGENCIA</th>";
tr += "<th>LOCALIZACIÓN</th>";
tr += "<th>DESACTIVADOR</th>";
tr += "</thead>";
tr += '<tbody id="tbody' + i +">';
tr += '<td class= "OIDCELL">' + response[i].usuario_oid + "</td>";
tr += "<td>" + response[i].fechainicio + "</td>";
tr += "<td>" + response[i].fechafin + "</td>";
tr += "<td>" + response[i].tipoemergencia_tipo
+ "</td>";
tr += "<td>" + enlace + "</td>";
if (response[i].desactivador == 0){
tr += '<td> <button type="button" onclick="cambiarDesactivador()">Desactivar</button></td>';
}else{
tr += "<td>" + response[i].desactivador + "</td>";
}
tr += "</tr>";
tr += "</tbody>";
}
t += tr;
document.getElementById("historicoUser").innerHTML += t;
}
So in which way am I able to get the value of the USUARIO column of the same row of the pressed button?
Thank you in advance!
Some comments on the code, which has many errors:
function(response) {...} is not a valid function declaration or expression
The t variable seems redundant
Don't mix the semantics of double and single quotes. Use single quotes for javascript, double for HTML (see below)
All that += is inefficient, just create a single string and assign it to tr like:
tr = '<thead>' +
'<th>USUARIO</th>' +
'<th>FECHA INICIO</th>' +
...
'<tbody id="tbody' + i + '">' +
...
To get the row of the button that is clicked, get a reference to the button then use closest to get the tr ancestor. Table rows have a cells collection, the first cell is index 0, etc.
So pass this from the listener, go up to the row then get the content of the first cell, e.g.
function getFirstCellContent(el) {
let row = el.closest('tr');
console.log(row.cells[0].textContent);
}
table {
border-left: 1px solid #999999;
border-top: 1px solid #999999;
border-collapse: collapse;
}
th, td {
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
}
<table>
<tr><td>One<td><button onclick="getFirstCellContent(this)">Click me</button>
<tr><td>Two<td><button onclick="getFirstCellContent(this)">Click me</button>
<tr><td>Three<td><button onclick="getFirstCellContent(this)">Click me</button>
</table>
You could directly pass in the value response[i].usuario_oid which you are showing in the column to your button's onClick function
example: cambiarDesactivador(response[i].usuario_oid)
Here is my script for displaying loading data onto my table:
function my_data(result,j){
console.log(result);
var length = result.length;
console.log(length);
j = Number(j);
$('#news_data tbody').empty();
for(var i = 0 ; i < length; i++){
j+=1;
var tr = "<tr>";
tr += "<td>"+ j +"</td>";
tr += "<td><a href='"+ result[i].product_id +"' target='_blank'>"
+result[i].product_name +"</a></td>";
tr += "<td>"+ result[i].product_price +"</td>";
tr += "</tr>";
$('#news_data tbody').append(tr);
}
}
And here is my search:
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
my_data(search);
} else {
my_data();
}
});
When I search I get the list of items filtered as undefined
I have a function that creates a table that consists of several elements all of which are taken from a saved file. The table has other information inside(url) Inside the table surname name and middle name(if exists) is put under one header "Full name". How can I modify this function so that it not only displays the name but makes it so that the name is also a url link?
var members = data.results[0].members;
createTable(members)
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td>" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</td>";
table += "<td>" + members[r].party + "</td>" + "<td>" + members[r].state + "</td>" + "<td>" + members[r].seniority + "</td>";
if (members[r].votes_with_party_pct === undefined) {
table += "<td>" + "-" + "</td>"
} else {
table += "<td>" + members[r].votes_with_party_pct + "%" + "</td>"
}
}
table += "<tr>";
}
document.getElementById("house-data").innerHTML = JSON.stringify(table);
}
function createTable(members) {
var table = "";
var cols = 1;
var rows = members.length;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td><a href=\"YOUR_LINK_HERE\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";
...
Replace YOUR_LINK_HERE with the URL you want.
If you want to use a variable, use:
table +=
"<td><a href=\""+url+"\">" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</a></td>";
i want to ask about my code..
i have made jquery server side function for diplaying data from database into a table. i made the code firstly working well but after i try to add more code for creating a thead before creating the tbody the code wont work..
this is the code i made..
please help me to solve this
// JavaScript Document
$(document).ready(function() {
$.ajax({
type:"POST",
url:"../php/absen/spl_inputselect_data.php",
success: function(data){
var list = JSON.parse(data);
for(var i=0; i < list.length; i++){
var tr = "<tr>";
theadData = '<tr>' +
'<th>Nama Karyawan</th>' +
'<th>Tanggal</th>' +
'<th>Bagian</th>' +
'<th>Cost Center</th>' +
'<th>Jam Mulai</th>' +
'<th>Jam Selesai</th>' +
'<th>Status Lembur</th>' +
'<th>Total Jam</th>' +
'<th>Tugas</th>' +
'</tr>';
tr += "<td>" +list[i]['no']+"</td>";
tr += "<td>" +list[i]['nama']+"</td>";
tr += "<td>" +list[i]['tanggal']+"</td>";
tr += "<td>" +list[i]['jam_mulai']+"</td>";
tr += "<td>" +list[i]['jam_selesai']+"</td>";
tr += "<td>" +list[i]['status']+"</td>";
tr += "<td>" +list[i]['total']+"</td>";
tr += "<td>" +list[i]['bagian']+"</td>";
tr += "<td>" +list[i]['cost']+"</td>";
tr += "<td>" +list[i]['tugas']+"</td>";
tr += "</tr>";
$("#check_data tbody").append(tr);
}
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
You should append your head directly to the table only once and not within the loop:
$(document).ready(function() {
$.ajax({
type:"POST",
url:"../php/absen/spl_inputselect_data.php",
success: function(data){
var list = JSON.parse(data);
if(list.length > 0)
{
$("#check_data thead").html('<tr>' +
'<th>Nama Karyawan</th>' +
'<th>Tanggal</th>' +
'<th>Bagian</th>' +
'<th>Cost Center</th>' +
'<th>Jam Mulai</th>' +
'<th>Jam Selesai</th>' +
'<th>Status Lembur</th>' +
'<th>Total Jam</th>' +
'<th>Tugas</th>' +
'</tr>');
for(var i=0; i < list.length; i++){
var tr = "<tr>";
tr += "<td>" +list[i]['no']+"</td>";
tr += "<td>" +list[i]['nama']+"</td>";
tr += "<td>" +list[i]['tanggal']+"</td>";
tr += "<td>" +list[i]['jam_mulai']+"</td>";
tr += "<td>" +list[i]['jam_selesai']+"</td>";
tr += "<td>" +list[i]['status']+"</td>";
tr += "<td>" +list[i]['total']+"</td>";
tr += "<td>" +list[i]['bagian']+"</td>";
tr += "<td>" +list[i]['cost']+"</td>";
tr += "<td>" +list[i]['tugas']+"</td>";
tr += "</tr>";
$("#check_data tbody").append(tr);
}
}
return false;
}
});
});
I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?
Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.
Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>