Check table values when loading html page with jQuery - javascript

I have recently started to use jQuery and I would like a little help, on a function that I would like to implement, in practice I have a html table in which for each row there is the course, professor, day, hour, status and a button to cancel my reservation, I initially created a small function in which when I click the button it changes the value of STATUS from ACTIVE to CANCEL and then through a post sends data to the server.
This is my code - I'm using a jsp page and I fill the columns using jstl
$(document).on('click', '.table-remove', function(e){
var row = $(this).closest('tr');
$(this).prop("disabled",true);
var col1=row.find('td:eq(0)').text();
var col2=row.find('td:eq(1)').text();
var col3=row.find('td:eq(2)').text();
var col4=row.find('td:eq(3)').text();
var col5=row.find('td:eq(4)').text();
var sessionValue= $("#hdnSession").data('value');
$.post("Serverlet_prenotazioni_disdette",{corso:col1,professore:col2,giorno:col3,ora:col4,stato:col5,user:sessionValue},
function(data){
row.find('td:eq(4)').html('Disdetta');
alert(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-responsive-md table-hover text-center" id="table">
<tr style="background-color:#17a2b8;color:white">
<th class="text-center">Utente</th>
<th class="text-center">Corso</th>
<th class="text-center">Professore</th>
<th class="text-center">Giorno</th>
<th class="text-center">Ora</th>
<th class="text-center">Stato</th>
<th class="text-center"> </th>
</tr>
<tr>
<c:forEach var = "rip" items = "${prenotazioni}">
<tr>
<td id="account" class="pt-3-half" contenteditable="false" name="account"><c:out value = "${rip.getAccount().getNickname()}"/></td>
<td id="corso" class="pt-3-half" contenteditable="false" name="corso"><c:out value = "${rip.getRipetizione().getCorso().getNome_Corso()}"/></td>
<td id="professore" class="pt-3-half" contenteditable="false" name="professore"><c:out value = "${rip.getRipetizione().getProfessore().getCognome()}"/></td>
<td id="giorno" class="pt-3-half" contenteditable="false" name="giorno"><c:out value = "${rip.getGiorno()}"/></td>
<td id="ora" class="pt-3-half" contenteditable="false" name="ora"><c:out value = "${rip.getOra()}"/></td>
<td id="stato" class="pt-3-half" contenteditable="false" name="stato"><c:out value = "${rip.getStato()}"/></td>
<td>
<span id="table-remove" class="table-remove"><button type="button" id="button-d" class="btn btn-success" >Prenota</button></span>
</td>
</tr>
</c:forEach>
I would like to make a function in which at the time of loading the page analyzes the STATUS column and where it finds "Deleted" I must disable the button and change the color of the text "Canceled" from black to red, while where State has value "Activate" he must do nothing
I tried to do this function
$(document).load('.table-remove',function(){
var row = $(this).closest('tr');
var text=row.find('td:eq(4)').text();
if(text==="Disdetta"){
$(this).prop("disabled",true);
}
});
but doing so no longer works

Here is a reduced example showing how you can do:
// on load...
$(document).ready(function() {
// ...for each row...
$('tbody tr').each(function() {
var $statusCell = $(this).find('td:first-child');
// ...get status
var status = $statusCell.text();
// if status is "Deleted"...
if (status === 'Deleted') {
// ...disable button...
$(this).find('button').prop('disabled', true);
// ...and change text color
$statusCell.css('color', 'red');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>title</title>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Deleted</td>
<td>
<button>Do something</button>
</td>
</tr>
<tr>
<td>Other status</td>
<td>
<button>Do something</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Related

jquery - show / hide elements rows by elemenst in data-id array

I have table with rows like that:
<tr class="listRow" data-id="[11,0]">...</tr>
<tr class="listRow" data-id="[1,2,3]">...</tr>
How i can using JQuery filter specific rows with element in array? For example by button click show all rows with 1 in array and hide rest.
Edit - my sample code so far:
i don't know how to filtering elements in data-id array.
$(document).on('click','#filterList',function()
{
var element = $(this).data("id");
// how to filter elements in rows
}
);
If i understand correctly:
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr class="listRow" data-id="[1,0]">
<th class="tg-0pky">Here is 1</th>
<th class="tg-0pky">xxxx</th>
<th class="tg-0pky"></th>
<th class="tg-0pky"></th>
</tr>
</thead>
<tbody>
<tr class="listRow" data-id="[11,0]">
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[15,0]" >
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[1,0,3]">
<td class="tg-0pky" >Here is 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
</tbody>
</table>
<button id="check">
Click
</button>
when you press the button, loop through all the elements that have a data-id
parse the data-id as json, which will give you an array
if the array includes the id you're looking for, set the class to hide or show (where they have the display css assigned accordingly)
here's what that might look like without jquery and using style and opacity. Usually it's done using class but this is for demonstration purposes, changing to use classes should be straight forward.
function findElsById(id){
var matches = []
document.querySelectorAll('[data-id]').forEach(function(el){
try{
var arr = JSON.parse(el.dataset.id)
if (arr.includes(id)) matches.push(el)
} catch (e){
// prolly not valid json
}
})
return matches
}
function show(id){
var els = findElsById(id);
console.log('show', id, '\nshowing: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:1'
})
}
}
function hide(id){
var els = findElsById(id);
console.log('hide', id, '\nhiding: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:0.1'
})
}
}
<table>
<tr class="listRow" data-id="[1,0]"><td>1, 0</td></tr>
<tr class="listRow" data-id="[1,2]"><td>1, 2</td></tr>
</table>
<button onclick="hide(0)">-0</button>
<button onclick="hide(1)">-1</button>
<button onclick="hide(2)">-2</button>
<button onclick="show(0)">+0</button>
<button onclick="show(1)">+1</button>
<button onclick="show(2)">+2</button>

How can I target a table cell in the same row with jQuery?

I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>
I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:
$("#85759.OrderDate").html('current date');
but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
$this = $(this);
$.post('updateOrder.php', {
type: 'updateOrder',
recid: recid,
conNote: conNote
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
$this.closest('td').addClass("has-error");
$("#serialNumberError").html(errorAlert);
$("#serialNumberError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
$this.closest('td').addClass("has-error");
//display AJAX error details
$("#serialNumberError").html(ajaxError);
$("#serialNumberError").show();
});
});
});
You can get the parent element 'tr' and then find the 'td.OrderDate', I suggest you to use a class to identify the td in the context of its parent.
$(function () {
$("input[type='text']").change(function() {
var parent = $(this).parents('tr');
// Get any element inside the tr
$('td.OrderDate', parent).text('[current date]')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>987654</td>
<td id="85760.OrderDate" class="OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</table>
You can select the cell by $this.closest('tr').children('td[id$="OrderDate"]').
You can simplify it more by:
Instead of using attribute ends with selector ([id$=".."]), if you can, add a CSS class "OrderDate" for example to all the order date cells, and simplify the selector to $this.closest('tr').children('.OrderData')
Instead of closest() use parents(). This is a micro-optimization. The only difference is that closest tests the actual element itself for matching the selector, and in this case you know you only need to check parent elements
You can also optionally rely on the fact that the cells are siblings and instead of children use siblings like like$this.parents('td').siblings('.OrderDate')
Check the code below. I've removed the ajax call and replaced it with the success block, but the concept is still the same. It gets the cell that has an id that ends with "OrderDate" on the same row and sets the html for that cell. I've used the jQuery Ends With selector for this.
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
var $this = $(this);
$this.parents('tr:first').find("td[id$='OrderDate']").html(new Date());
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
});
});
.has-success {
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>

get the values of all cells in table row using jquery

I would like to get the values in each cell in table row which is selected using a checkbox.
Scenario: Whenever user clicks the show table button, my page is dynamically loaded with some data from tables, which has columns like checkbox, Item name, Item code, Quantity, Rejected and Accepted. Now I want to get the values of selected rows when the user clicks the button called "save".
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.post('PopulateTable',{grn : $('#grn').val()},function(responseJson) {
if(responseJson!=null){
$("#itemtable").find("tr:gt(0)").remove();
var table1 = $("#itemtable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).html('<input type="checkbox" />');
rowNew.children().eq(1).text(value['itemname']);
rowNew.children().eq(2).text(value['itemcode']);
rowNew.children().eq(3).text(value['supplier']);
rowNew.children().eq(4).text(value['receivedqty']);
rowNew.children().eq(5).html('<input type="text" class="tb2"/>');
rowNew.children().eq(6).html('<input type="text" class="tb2"/>');
rowNew.children().eq(7).html('<input type="text" class="tb2"/>');
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
<br/>
<div id="tablediv">
<table cellspacing="0" id="itemtable" align="center">
<tr>
<td><input type="checkbox" /></td>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
</table>
</div>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#itemtable").on('click','.btnSelect',function(){
// get the current row
alert("i am inside select");
// get the current row
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2=currentRow.find("td:eq(1)").text(); // get item name
var col3=currentRow.find("td:eq(2)").text(); // get item code
var col4=currentRow.find("td:eq(3)").text(); // get supplier
var col5=currentRow.find("td:eq(4)").text(); // get received qty
var col6=currentRow.find("td:eq(5)").text(); // get accepted qty
var col7=currentRow.find("td:eq(6)").text(); // get rejected qty
var col8=currentRow.find("td:eq(7)").text(); // get remarks
var data=col1+"\n"+col2+"\n"+col3+"\n"+col4+"\n"+col5+"\n"+col6+"\n"+col7+"\n"+col8;
alert(data);
});
});
<!--btnSelect is class of checkbox -->
I come across below exaple to get all value of table cell of checked row.
$('.chk').change(function () {
if($(this).is(':checked'))
{
$(this).closest('tr').find('td').each(
function (i) {
console.log($(this).text());
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tablediv">
<table border="1" id="itemtable" align="center">
<tr>
<th>check</th>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
<tr>
<td><input type="checkbox" class="chk" ></td>
<td>Pencil</td>
<td>101</td>
<td>Supplier</td>
<td>10</td>
<td>5</td>
<td>5</td>
<td>Remarks</td>
</tr>
<tr>
<td><input type="checkbox" class="chk" ></td>
<td>Pen</td>
<td>102</td>
<td>Supplier</td>
<td>25</td>
<td>20</td>
<td>5</td>
<td>Remarks</td>
</tr>
</table>
</div>
First give "name" to your checkbox, such as :
<input type="checkbox" name="case[]" />
JS code:
var values = new Array();
$("#saveButton").click(function(){
$.each($("input[name='case[]']:checked"), function() {
var data = $(this).parents('tr:eq(0)');
values.push({ 'Item name':$(data).find('td:eq(1)').text(), 'Item code':$(data).find('td:eq(2)').text() , 'Supplier':$(data).find('td:eq(3)').text()});
});
console.log(JSON.stringify(values));
});
Please check out the EXAMPLE

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

how to get values of columns for a selected row through jQuery on click of element calling method to retrieve value

here i am trying to fetch values of a particular column for a selected row via jquery.In Following code i have two rows which do not have any id.I tried following way and getting both rows value for that column appending each other.how to get value for that row only using jquery only.I want to call test function on click of that element, dont want to use http://jsfiddle.net/SSS83/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function test(){
var id = $(".use-address").closest("tr").find('td:eq(2)').text();
alert(id);
}
</script>
</head>
<body>
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td class="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Glas</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
<tr>
<td class="nr"><span>30</span>
</td>
<td>Some Street 2</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Not sure why you don't want to use jQuery Click event!!
Any way, if you want to stick with your test function, you need to tell the function from where it got called.
so change the
<button type="button" class="use-address" onclick="test();">Use</button>
to
<button type="button" class="use-address" onclick="test(this);">Use</button>
And update your test function as
function test(el) {
var id = $(el).closest("tr").find('td:eq(2)').text();
alert(id);
}
Enjoy!!
If you change your mind you can use the following code
jQuery('document').ready(function() {
jQuery('.use-address').on('click',function() {
var id = $(this).closest("tr").find('td:eq(2)').text();
alert(id);
})
});
Based on a click of a TD:
$('td').on('click',function() {
//get the column of the TD
var myCol = $(this).index();
//loop through the rows of this table, get the TD in the same column
$(this).parent('table').find('tr').each(function() {
var colValue = $(this).find('td').eq(myIndex).html()
}
})
"colValue" in the loop will grab the contents of the TD at that position.

Categories

Resources