2 Tables on one page - buttons on Rows to run different script - javascript

I have a page with 2 tables and each row has a 'Select' button which needs to run a script when clicked. I've got this working with the first table but can't work out how to get it working with both tables.
Here's the HTML for the tables:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h2>Select Main</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK5543333">
<td>BJ2345</td>
<td>Laptop 13 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK3241235213">
<td>AZ77656</td>
<td>Laptop 15 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
<h2>Select Accessories</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK3412541">
<td>MM42412341</td>
<td>Mouse</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK95390485">
<td>KB42341243</td>
<td>Keyboard</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK42353">
<td>USB421341234</td>
<td>USB Adapter</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK543647585">
<td>PWR363456534</td>
<td>POWER ADAPTER</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
I need to run a different script when users select from the top/Main table and another script when users select from the bottom/Accessories table. Here's my script that runs when the Select button from the first table is clicked:
$(document).ready(function() {
$('button.btn-success:not([type="submit"])').click(function() {
// Remove the classes from all of the TR elements
$(this).parents('table').find('tr').removeClass('success warning danger');
var productID = $(this).closest('tr').attr('id');
console.log(productID);
$this = $(this);
// add the success class to the row and remove the danger class if it was present
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
// update the hidden input with the selected productID
$('#productID').val(productID);
});
});
Not sure how to have another version of this that only runs when the Select button from the 2nd table is clicked?

Was interrupted writing the answer but you could try something like this:
const selectHelper =
($me,classToAdd,inputSelector) => {
$me.parents("table")
.eq(0)
.find("tr")
.removeClass("success warning danger");
const id =
$me.parents("tr")
.eq(0)
.addClass(classToAdd)
.attr("id")
;
$(inputSelector).val(id);
}
;
const clickActions = {
one:(e,$me)=>
selectHelper(
$me
,"warning"
,"#inputidOne"
)
,two:(e,$me)=>
selectHelper(
$me
,"success"
,"#inputidTwo"
)
};
$(document.body)
.on(
"click"
,`[data-action-click]`
,e=>{
const action = e.target.getAttribute("data-action-click");
if(typeof clickActions[action] === "function"){
clickActions[action](e,$(e.target))
}
debugger;
}
)
The button needs a data-action-click attribute that has the name of the function you want to execute when clicked:
<button
type="button"
data-action-click="two"
class="btn btn-success btn-sm"
>
Select
</button>

I believe this is what you're looking for:
$(document).ready(function() {
$("table:first").find('button[type!="submit"]').click(function() {
$("table:first").find("tr").removeClass("success warning danger");
$(this).parents("tr").addClass("success");
$("#productID").val($(this).parents("tr").attr("id"));
});
$("table").eq(1).find('button[type!="submit"]').click(function() {
$("table").eq(1).find("tr").removeClass("success warning danger");
//Do whatever color you want
$(this).parents("tr").addClass("warning");
//Wasn't provided this snippet so I just made up accessoryID
$("#accessoryID").val($(this).parents("tr").attr("id"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h2>Select Main</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
<tr id="SK5543333">
<td>BJ2345</td>
<td>Laptop 13 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr id="SK3241235213">
<td>AZ77656</td>
<td>Laptop 15 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
<h2>Select Accessories</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
<tr id="SK3412541">
<td>MM42412341</td>
<td>Mouse</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr id="SK95390485">
<td>KB42341243</td>
<td>Keyboard</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr id="SK42353">
<td>USB421341234</td>
<td>USB Adapter</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr id="SK543647585">
<td>PWR363456534</td>
<td>POWER ADAPTER</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
.eq This returns a jQuery object from a list of jQuery objects by index, whereas indexing with brackets will return HTML content.
P.S. You don't really need class="" and scope="col" in the table, the HTML I provided doesn't have those. The only real point of the class attribute is to assign multiple CSS attributes easily, unless you're using classes as selectors. Same with scope, I've made many tables and never used scope.
Also, when you do a thead, you need to add a tr before you add the headers. I fixed that in the code above. (Yes, this does mean that tables support multiple header rows).

Related

Sorting A Table With Tabs & Javascript

I'm hoping someone can help me out. I have created a table and have multiple Tabs. Each Tab has different data inside the table. Each table row has a column with a number of votes and I want to sort the rows automatically with the columns that have more votes at the top.
This is my HTML code:
<div class="row" style="text-align: center;">
<div class="container" style="margin-top: 8%;">
<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="pills-comedy-tab" data-bs-toggle="pill" data-bs-target="#pills-comedy" type="button" role="tab" aria-controls="pills-comedy" aria-selected="false">COMEDY MOVIES</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="pills-horror-tab" data-bs-toggle="pill" data-bs-target="#pills-horror" type="button" role="tab" aria-controls="pills-horror" aria-selected="false">HORROR MOVIES</button>
</li>
</ul>
<div class="tab-content" id="pills-tabContent">
<!--START OF COMEDY MOVIES TAB-->
<div class="tab-pane fade show active" id="pills-comedy" role="tabpanel" aria-labelledby="pills-comedy-tab">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Director</th>
<th scope="col" class="d-none d-md-table-cell">Starring</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Hot Rod</td>
<td>Akiva Schafer</td>
<td class="d-none d-md-table-cell">Andy Samberg</td>
<td><span class="vote">38</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Game Night</td>
<td>Jonathon Goldstein</td>
<td class="d-none d-md-table-cell">Jason Bateman</td>
<td><span class="vote">99</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">3</th>
<td>The First Wives Club</td>
<td>Hugh Wilson</td>
<td class="d-none d-md-table-cell">Keenan Wayans</td>
<td><span class="vote">21</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">4</th>
<td>Scary Movie</td>
<td>Keenan Wayans</td>
<td class="d-none d-md-table-cell">Marlon Wayons</td>
<td><span class="vote">1</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">5</th>
<td>Blockers</td>
<td>Kay Cannon</td>
<td class="d-none d-md-table-cell">Leslie Mann</td>
<td><span class="vote">11</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">6</th>
<td>The Bank Dick</td>
<td>Eddie Cline</td>
<td class="d-none d-md-table-cell">W.C Fields</td>
<td><span class="vote">87</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">7</th>
<td>Mrs Doubtfire</td>
<td>Chris Columbus</td>
<td class="d-none d-md-table-cell">Robin Williams</td>
<td><span class="vote">38</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
</tbody>
</table>
</div>
<!--END OF COMEDY MOVIES TAB-->
<!--START OF HORROR MOVIES TAB-->
<div class="tab-pane fade" id="pills-horror" role="tabpanel" aria-labelledby="pills-horror-tab">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Director</th>
<th scope="col" class="d-none d-md-table-cell">Starring</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Acacia</td>
<td>Park Ki-Young</td>
<td class="d-none d-md-table-cell">$50,000,000</td>
<td><span class="vote">38</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">2</th>
<td>Dead End</td>
<td>Fabrise Canepa</td>
<td class="d-none d-md-table-cell">Ray Wise</td>
<td><span class="vote">38</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">3</th>
<td>Malefic</td>
<td>Steve Sessions</td>
<td class="d-none d-md-table-cell">Cynder moon</td>
<td><span class="vote">99</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">4</th>
<td>Love Object</td>
<td>Robert Parigi</td>
<td class="d-none d-md-table-cell">Udo Kier</td>
<td><span class="vote">125</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">5</th>
<td>Jeepers Creepers II</td>
<td>Victor Salva</td>
<td class="d-none d-md-table-cell">Jonathan Breck</td>
<td><span class="vote">3368</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">6</th>
<td>Into The Mirror</td>
<td>Kim Sung-Ho</td>
<td class="d-none d-md-table-cell">Yoo Ji-Tae</td>
<td><span class="vote">380</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
<tr>
<th scope="row">7</th>
<td>Threshold</td>
<td>Chuck Bowman</td>
<td class="d-none d-md-table-cell">Nicholas lea</td>
<td><span class="vote">32</span></td>
<td> <button type="button" class="btn btn-primary">UPVOTE</button></td>
</tr>
</tbody>
</table>
</div>
<!--END OF HORROR MOVIES TAB-->
</div>
</div>
</div>
</div>
This is the Javacript code I am using to sort by the vote column
$(document).ready(function(e) {
var dataRows = [];
//Create an array of all rows with its value (this assumes that the amount is always a number. You should add error checking!! Also assumes that all rows are data rows, and that there are no header rows. Adjust selector appropriately.
$('tr').each(function(i, j) {
dataRows.push({ 'vote': parseFloat($(this).find('.vote').text()), 'row': $(this) });
})
//Sort the data smallest to largest
dataRows.sort(function(a, b) {
return b.vote - a.vote;
});
//Remove existing table rows. This assumes that everything should be deleted, adjust selector if needed :).
$('table').empty();
//Add rows back to table in the correct order.
dataRows.forEach(function(ele) {
$('table').append(ele.row);
})
});
So What I have noticed is if I run this code it does sort by column, but it also removes the table from the HORROR TAB and places inside the COMEDY TAB and makes duplicates. If I remove the tabs then everything is fine. So something somewhere is messing with the sorting by having tabs and i just can't figure out whats going on.
I could really use some help, i've been trying to figure this out for days.
Thanks guys
Having separate arrays for each tab(comedy and horror) worked for me, so you just create a second array and duplicate the javascript functions, using more specific JS selectors.
var dataRows1 = []
var dataRows2 = []
function sortRows() {
//Create an array of all rows with its value (this assumes that the amount is always a number. You should add error checking!! Also assumes that all rows are data rows, and that there are no header rows. Adjust selector appropriately.
$('#pills-comedy tr').each(function () {
dataRows1.push({
'vote': parseFloat($(this).find('.vote').text()),
'row': $(this)
});
})
$('#pills-horror tr').each(function () {
dataRows2.push({
'vote': parseFloat($(this).find('.vote').text()),
'row': $(this)
});
})
//Sort the data smallest to largest
dataRows1.sort(function (a, b) {
return b.vote - a.vote;
});
dataRows2.sort(function (a, b) {
return b.vote - a.vote;
});
//Remove existing table rows. This assumes that everything should be deleted, adjust selector if needed :).
$('#pills-comedy table').empty();
$('#pills-horror table').empty();
//Add rows back to table in the correct order.
dataRows1.forEach(function (ele) {
$('#pills-comedy table').append(ele.row);
})
dataRows2.forEach(function (ele) {
$('#pills-horror table').append(ele.row);
})
};
This works for what you intended, but at least here it's still breaking some of the Bootstrap layout and I'm not sure why now, need to dig into this.

adding a new cell to a table using javascript

I have a button which is named reject and when it is clicked it is supposed to show a form with a text and another button.
Everything is working fine except it only add a cell to the first row only, no matter where the reject button is or whether it in the second or third row it will show the new cell after the first row.
i want the small form to be added in the same row where the reject button was clicked.
this my code:
<table asp-controller="Home" asp-action="Pending" class="table table-bordered table-sm table-striped" id="myTable">
<thead>
<tr>
<th>Id</th>
<th>Email</th>
<th>Status</th>
<th>Check Time</th>
</tr>
</thead>
<tbody id="demo">
#if (Model == null)
{
<tr>
<td colspan="7" class="text-center">No Model Data</td>
</tr>
}
else
{
#foreach (var p in Model)
{
<tr>
<td>#p.Id</td>
<td>#p.Email</td>
#if (#p.CheckOut == null)
{
<td>Offline</td>
<td>#p.CheckIn</td>
}
else
{
<td>Online</td>
<td>#p.CheckOut</td>
}
<td>
<button name="button" value="accept" asp-action="Accept" asp-route-id="#p.Id" class="btn btn-success">Accept Request</button>
<button id="re" class="btn btn-danger" data-id="#p.Id" onclick="fun()">Reject Request</button>
</td>
<td style="display:none;" id="comment">
<form >
<input type="text" name="newcomment" id="newcomment" />
<button name="button" value="reject" asp-action="Reject" asp-route-id="id" class="btn btn-primary">Comment</button>
</form>
</td>
</tr>
}
}
</tbody>
</table>
<script type="text/javascript">
function fun() {
document.getElementById("comment").style.display = 'block';
}
You can use JQuery to show the td area .
Firstly , modify this line :
<button id="re" class="btn btn-danger" data-id="#p.Id" onclick="fun()">Reject Request</button>
To
<button id="re" class="btn btn-danger" data-id="#p.Id" onclick="fun(this)">Reject Request</button>
And modify your js function to find the next td of current button :
function fun(elem) {
$(elem).closest('td').next('td').show();
}

Set Buttons to run Different Scripts

I have a page with 2 tables and each row has a 'Select' button which needs to run a script when clicked. I've got this working with the first table but can't work out how to get it working with both tables.
Here's the HTML for the tables:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h2>Select Main</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK5543333">
<td>BJ2345</td>
<td>Laptop 13 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK3241235213">
<td>AZ77656</td>
<td>Laptop 15 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
<h2>Select Accessories</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK3412541">
<td>MM42412341</td>
<td>Mouse</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK95390485">
<td>KB42341243</td>
<td>Keyboard</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK42353">
<td>USB421341234</td>
<td>USB Adapter</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK543647585">
<td>PWR363456534</td>
<td>POWER ADAPTER</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
I need to run a different script when users select from the top/Main table and another script when users select from the bottom/Accessories table. Here are the 2 scripts that I would like to run when the Select button is clicked in either table (first script for the top table and 2nd script for the 2nd table):
$(document).ready(function() {
$('button.btn-success:not([type="submit"])').click(function() {
// Remove the classes from all of the TR elements
$(this).parents('table').find('tr').removeClass('success warning danger');
var productID = $(this).closest('tr').attr('id');
console.log(productID);
$this = $(this);
// add the success class to the row and remove the danger class if it was present
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
// update the hidden input with the selected productID
$('#productID').val(productID);
});
});
$(document).ready(function() {
$('button.btn-success:not([type="submit"])').click(function() {
var itemID = $(this).closest('tr').attr('id');
// Create a reference to $(this) here:
$this = $(this);
$.post('updateAccessories.php', {
itemID: itemID
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating your selections - ' + ajaxError + '. Please contact the Help Desk';
$this.closest('tr').addClass("warning");
$('#alert_ajax_error').html(errorAlert);
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
if ($this.closest('tr').hasClass("success")) {
$this.closest('tr').removeClass("success");
} else {
$this.closest('tr').addClass("success");
}
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating your selections - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Help Desk';
$this.closest('tr').addClass("warning");
$('#alert_ajax_error').html(ajaxError);
$("#alert_ajax_error").show();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
At the moment clicking either button runs both scripts which I can understand as they both meet the criteria for:
$('button.btn-success:not([type="submit"])').click(function() {
but I'm not experienced enough to know how to make the necessary changes to have each button run a different script here?
A very basic way to differentiate between buttons would be to add an attribute called "id" to them.
<button id="button1" type="button" class="btn btn-success btn-sm">Select</button>
<button id="button2" type="button" class="btn btn-success btn-sm">Select</button>
Now you can reference each like this:
$('#button1').click(function() { ...
$('#button2').click(function() { ...
If you can change the markup then add a class from main and another for accessories in the button and do $('button.main') and $('button.accessories') instead of $('button.btn-success:not([type="submit"])')
If not then you need to be able to discern one from another.
$(document).ready(function() {
$('button.btn-success:not([type="submit"])').click(function(e) {
var t = $(e.target).parent().parent().parent().parent().parent().prev()[0].innerHTML;
if(t.indexOf("Main") !== -1) {
// Has MAIN - put your main code in here
console.log("main stuff");
} else if (t.indexOf("Accessories") !== -1) {
// It's Accessories - put your accessories code in here
console.log("accessories stuff");
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<h2>Select Main</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK5543333">
<td>BJ2345</td>
<td>Laptop 13 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK3241235213">
<td>AZ77656</td>
<td>Laptop 15 inch display</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>
<h2>Select Accessories</h2>
<div>
<br />
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Code</th>
<th scope="col">Description</th>
<th class="text-center" scope="col">Select</th>
</thead>
<tbody>
<tr class="" id="SK3412541">
<td>MM42412341</td>
<td>Mouse</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK95390485">
<td>KB42341243</td>
<td>Keyboard</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK42353">
<td>USB421341234</td>
<td>USB Adapter</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
<tr class="" id="SK543647585">
<td>PWR363456534</td>
<td>POWER ADAPTER</td>
<td class="text-center"><button type="button" class="btn btn-success btn-sm">Select</button></td>
</tr>
</tbody>
</table>
</div>

How to pass data-key value of clicked Table row when click on Button

I have a table with some rows and each tow has an data-key value. Now I select one of those rows and want to click on a button in order to forward this data-key value as an GET value. I don't really know how to capture this selected data-key. Kindly asking for help.
Here is a fiddle: fiddle
Below is my snippet so far.
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
<div class="form-horizontal" style="margin-top:5em;">
<div class="input-group">
<input class="form-control form-control-sm" id="FunctionBookSearchForEvents" placeholder="Search for Events" style="font-size:12px;">
<button class="btn btn-sm btn-secondary" href="events.phtml?TableID=''" data-id="" style="margin-left:1em; font-size:12px;">Add Event</button>
</div>
<div id="Table">
<table class="table table-sm table-hover">
<thead>
<tr>
<th>ID</th>
<th>Event Name</th>
</tr>
</thead>
<tbody>
<tr class="clickable-row" data-key="12">
<td>12</td>
<td>Test Event 12</td>
</tr>
<tr class="clickable-row" data-key="13">
<td>13</td>
<td>Test Event 13</td>
</tr>
</tbody>
</table>
</div>
</div>
You could try to implement this code.
I will add modified version of your code, but I will mark out where I modified it.
<div class="container-fluid">
<div class="form-horizontal" style="margin-top:5em;">
<div class="input-group">
<input class="form-control form-control-sm" id="FunctionBookSearchForEvents" placeholder="Search for Events" style="font-size:12px;">
<button class="btn btn-sm btn-secondary" href="events.phtml?TableID=''" data-id="" onclick="addEvent();" style="margin-left:1em; font-size:12px;">Add Event</button>
</div>
<div id="Table">
<table class="table table-sm">
<thead>
<tr>
<th>ID</th>
<th>Event Name</th>
</tr>
</thead>
<tbody>
<tr onclick="test(this);"> // MODIFIED, This line would be added onto all your rows that you want clickable.
<td>12</td>
<td>Test Event 12</td>
</tr>
<tr onclick="test(this);">
<td>13</td>
<td>Test Event 13</td>
</tr>
</tbody>
</table>
</div>
</div>
Now I will show you the implementation of the function test.
function test(element){
console.log(element.innerHTML);
}
Now, you could do anything with this element callback. For example, you could store it in a variable and send that to a PHP page using AJAX, when you press a button.
Edit 1
First, I want to point out that you cannot use <button> as a link.
First, there are a few modifications to the HTML.
<button id="submitButton" class="btn btn-sm btn-secondary" onclick="addEvent();" data-id="" style="margin-left:1em; font-size:12px;">Add Event</button>
Here we added an id, "submitButton" and an onclickEvent which will call the function addEvent.
This is the function addEvent:
function addEvent(){
if(currentRow == undefined){
alert("Select a row");
return;
}
var link = "events.phtml?TableID="+currentRow.cells[0].innerHTML;
}
This link variable can easily be implemented using an AJAX call with jQuery or just plain javascript.
Sidenote
The function test has also been edited.
function test(element){
currentRow = element;
}
I recommend editing the name on the function test so that the code will look more organised.
Edit 2
If I have understood what you want out of this, this will be the new fix.
So you will have to edit the HTML again.
<div class="container-fluid">
<div class="form-horizontal" style="margin-top:5em;">
<div class="input-group">
<input class="form-control form-control-sm" id="FunctionBookSearchForEvents" placeholder="Search for Events" style="font-size:12px;">
<button class="btn btn-sm btn-secondary" href="events.phtml?TableID=''" data-id="" onclick="addEvent();" style="margin-left:1em; font-size:12px;">Add Event</button>
</div>
<div id="Table">
<table class="table table-sm">
<thead>
<tr>
<th>ID</th>
<th>Event Name</th>
</tr>
</thead>
<tbody>
<tr onclick="test(this);" data-key="12"> // MODIFIED, This line would be added onto all your rows that you want clickable.
<td>12</td>
<td>Test Event 12</td>
</tr>
<tr onclick="test(this);" data-key="13">
<td>13</td>
<td>Test Event 13</td>
</tr>
</tbody>
</table>
</div>
</div>
You will need to make a slight change to the javascript as well.
function addEvent(){
if(currentRow == undefined){
alert("Select a row");
return;
}
var link = "events.phtml?TableID="+currentRow.getAttribute("data-key");
}
You still use this address for anything you like, for example an AJAX request.

How get the value in <tr>

I need to get the text in <tr>. This is my html code:
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente"><tr id="aggiungiprova"><td>prova</td><td><button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i></button></td></tr></tbody>
</table>
I need to extract the first <td> in <tr> that is "prova" in this example so I use this jquery code:
$('#tbody_aggiungi_utente').children('tr').each(function(i) {
console.log("TABELLA " + JSON.stringify(i)+" Tabella "+JSON.stringify($(this)));
//array_user.push($(this).attr('id').replace('aggiungi', ''));
});
But it doesn't work because it prints me TABELLA 0 Tabella {"0":{},"context":{},"length":1}
Anyone can help me?
$('#tbody_aggiungi_utente').children('tr').each(function(i) {
console.log("TABELLA " + JSON.stringify(i)+" Tabella "+$(this).first().text());
//array_user.push($(this).attr('id').replace('aggiungi', ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova"><td>prova</td><td><button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i></button></td></tr>
</tbody>
</table>
You should use a better selector instead of children. Then you need do select the td inside your each.
$('#tbody_aggiungi_utente tr').each(function(i) {
var firstTd = $("td:eq(0)", this);
console.log("TABELLA " + JSON.stringify(i) + " Tabella " + JSON.stringify(firstTd.text()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova">
<td>prova</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
Or you loop the td's directly:
$('#tbody_aggiungi_utente tr td:first-of-type').each(function(i) {
console.log("TABELLA " + JSON.stringify(i) + " Tabella " + JSON.stringify($(this).text()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova">
<td>prova</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i>
</button>
</td>
</tr>
<tr id="aggiungiprova">
<td>prova 2</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
replace each(function(i) with each(function(i,v) and then console.log( $(v).text().trim());
Output will be 'prova'
$('#tbody_aggiungi_utente').children('tr').each(function(i,v) {
console.log( $(v).text().trim());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova">
<td>prova</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm">
<i class="fa fa-times" aria-hidden="true"></i></button>
</td>
</tr>
</tbody>
</table>
Use children.
$(this).children('td:eq(0)').html());
$('#tbody_aggiungi_utente > tr').each(function(i) {
console.log("TABELLA " + JSON.stringify(i)+
" Tabella "+JSON.stringify($(this).children('td:eq(0)').html()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova"><td>prova</td><td><button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i></button></td></tr>
<tr id="aggiungiprova1"><td>prova1</td><td><button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i></button></td></tr>
</tbody>
</table>
Take a look at CSS Selectors. jQuery can select elements using the same methods.
console.log(jQuery("#aggiungiprova td:first-child"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova">
<td>prova</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
This should work...
a = $('#tabella_username_aggiunti tr th')
console.log(a.text())
//or
a.each(function(a, el) {
console.log($(el).text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" style="" id="tabella_username_aggiunti">
<thead>
<tr>
<th>Username</th>
<th>Cancella</th>
</tr>
</thead>
<tbody id="tbody_aggiungi_utente">
<tr id="aggiungiprova">
<td>prova</td>
<td>
<button id="eliminaprova" type="button" class="btn btn-danger btn-sm"><i class="fa fa-times" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
$("#aggiungiprova td").first().text();
Gives the content of the first td in the tr named "aggiungiprova".
If you need to get all names in the entire list, then:
var names = [];
$("#tabella_username_aggiunti tr").each(function(){
names.push( $("td",this).first().text());
});
// names is now an array of all names
Or you name [sic] all name TDs with class and iterate them for easier-to-read code and faster execution:
<table>
<tr><td class="name-cell">My Name</td><td>other things</td></tr>
<tr><td class="name-cell">My Name</td><td>other things</td></tr>
</table>
JS:
$('.name-cell').each(function(){
// $(this).text()
});

Categories