Target closest Table Row when button inside of TD is clicked jQuery - javascript

So. I have this table:
<table>
<tr>
<td>Element1</td>
<td>Element1</td>
<td>Element1</td>
<td><a id="btn" href=#">Accept</a></td>
</tr>
<tr>
<td>Element2</td>
<td>Element2</td>
<td>Element2</td>
<td><a id="btn" href=#">Accept</a></td>
</tr>
</table>
What I want to do is: Button gets clicked, it gets hidden and the respective <tr> gets border: 1px solid black;.
I'm kinda new to jQuery and can't figure out how to select the 2nd parent of an element. Any help would be appreciated

your buttons are using the same id value. you have to use class
Also you don't need to use jQuery. please follow this code
const btns = document.querySelectorAll('.id');
btns.forEach((btn) => {
btn.addEventListener('click', (e) => {
e.preventDefault();
e.target.closest('tr').style.cssText = "border:1px solid black";
e.target.remove();
})
});
table {
border-collapse: collapse
}
<table>
<tr>
<td>Element1</td>
<td>Element1</td>
<td>Element1</td>
<td><a class="id" href=#">Accept</a></td>
</tr>
<tr>
<td>Element2</td>
<td>Element2</td>
<td>Element2</td>
<td><a class="id" href=#">Accept</a></td>
</tr>
</table>

Related

Get dataset item from html <a> element using jquery

I have an element within a table in html:
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
and i need to get the value of the "data-productid" attribute
at the moment i have this code:
$(document).ready(function(){
$('#href0').click(function(event) {
event.preventDefault()
console.log(this.dataset.productid)
return false;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
and nothing is being printed in the console.
I am using handlebars
We managed to establish you are using Handlebars templating
What MIGHT then be the case is your links are inserted dynamically when you compile the handlebars.
If that is the case you need to delegate and then this question is a duplicate of Event binding on dynamically created elements?
$(document).ready(function(){
// document or the nearest STATIC container
$(document).on('click','[data-productid]',function(event) {
event.preventDefault()
console.log(this.dataset.productid)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
<td><a id="href0" href="#" data-productid="1">Product 2</a></td>
You dont need to the a in the td at all (or even the id on the a or the td) - simply apply the click handler to the td and have the data attribute on that so that when it is clicked - the console will log the data attribute.
$(document).ready(function(){
$('td').click(function() {
let id = $(this).attr('data-productid');
console.log('The product id is ' +id)
})
});
table {
border-collapse: collapse
}
td {
border:solid 1px #d4d4d4;
padding: 10px 20px;
border-collapse: collapse
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-productid="1">Product 1</td>
<td data-productid="2">Product 2</td>
</tr>
<tr>
<td data-productid="3">Product 3</td>
<td data-productid="4">Product 4</td>
</tr>
</table>
If you absolutely must have the a - then its the same as above - just applied to the different element
$(document).ready(function(){
$('a').click(function(event) {
event.preventDefault();
let id = $(this).attr('data-productid');
console.log('The product id is ' +id)
})
});
table {
border-collapse: collapse
}
td {
border:solid 1px #d4d4d4;
padding: 10px 20px;
border-collapse: collapse
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Product 1</td>
<td>Product 2</td>
</tr>
<tr>
<td>Product 3</td>
<td>Product 4</td>
</tr>
</table>

How to change color of selected row on onmousedown event

I am trying to change the color of the selected row from a table on a onmousedown event and reset all others (or keep them the same) . Only one row can be red at a time while all others are green.
What I have tried:
function HighLight(id) {
var rows = $('#tbl > tbody > tr').each(function(elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v3
</td>
</tr>
</table>
Ideally I would like to store the old selected row so that I won't reset all others at each new selection, but in case I can't reset all would do it.
P.S I need to make due with the id that i am provided.I am using interop so the id is coming from the exterior. All my tr have that method injected in them.
The function name is wrong its Highlight not HighLight
To pass the id of the element on function call you cannot just pass any variable(e in your case). Use this.getAttribute('id') to get the id.
In the each() the argument elem represented the index of the element and not the element itself. Introduce another argument for index.
function Highlight(id) {
var rows = $('#tbl > tbody > tr').each(function(i,elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v3
</td>
</tr>
</table>
Here is a quick example on how can you do that.
$("table tr").on('click', function(){
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
});
table tr {
background: green;
}
table tr.highlighted {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Here is how it works:
It binds a click event to every row in the table (tr),
Every time you click on a row, all elements that has a class called highlighted loose it and the row that you clicked gets the class highlighted,
In css you can change the default background color for all rows and the color after highlighting.
If you don't want to use a css, here is similar function but instead of adding and removing class it does the same with the inline css property.
$("table tr").on('click', function(){
$("table tr").css("background", "green");
$(this).css("background", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background: green;">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background: green;">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background: green;">
<td>
v3
</td>
</tr>
</table>
But I do not recommend the second solution.
You can have two css classes; one for selected row and other for remaining rows.
On click of the row, you can add the "selected" class to that row.
$("#tbl tr").click(function(){
var $this = $(this);
//remove the previous row selection, if any
$("#tbl tr.selected").removeClass("selected");
//add selected class to the current row
$this.addClass("selected");
});
#tbl tr{
background-color: aquamarine;
}
#tbl tr.selected{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2" >
<td>
v2
</td>
</tr>
<tr id="tr3" >
<td>
v3
</td>
</tr>
</table>
You can do like this.by using class you can carry out other operations
$("#tbl").on("click", "tr", function() {
$(' tr').removeClass("Red")
$(this).addClass("Red")
});
.Red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Several issues:
JS is case sensitive, so Highlight and HighLight (capital L) is not the same. I renamed the HighLight function to Highlight (lowercase l)
Use parameter this on function call in event handler attribute. This hands over the HTML element of the event handler attribute over to the event handler function (Highlight in your case)
Callback function of jQuery's each method has the index as a first parameter and the element as second
This makes your code work
function Highlight(tr) {
var rows = $('#tbl > tbody > tr').each(function(index, elem) {
elem.style.backgroundColor = 'green';
})
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>
There are some more things you can do to enhance your code
Don't use style in your JS code, but set classes for CSS
Don't use HTML onmousedown attributes, but JS addEventListeners
Replace jQuery code with VanillaJS
console.clear()
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.addEventListener('mousedown', Highlight)
}
function Highlight(e) {
e.preventDefault()
const tr = this
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.classList.remove('highlight')
row.classList.add('highlight-siblings')
}
tr.classList.remove('highlight-siblings')
tr.classList.add('highlight')
}
/* 1. */
tr {
background-color: aquamarine;
}
tr.highlight-siblings{
background-color: green;
}
tr.highlight{
background-color: red;
}
<table id="tbl">
<tr>
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr>
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr>
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>

Add different custom tables to DOM by click event with Jquery

I have the following table with buttons on a simple HTML.
I need the buttons to be able to remove the current table and draw a new table (with a different content) to the DOM without reloading the page.
I have a JQuery method for removing the current table element, however I struggle with adding another table.
How can a table be added efficiently?
<!DOCTYPE HTML>
<html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<style>
.header-class{
font-size:25px;
font-family:cursive;
background-color:lightgray;
cursor:pointer;
}
.members {
font-family:helvetica;
}
.blips {
color:red;
}
.crudz {
color:blue;
}
.satin-flings {
color:rgb(213, 194, 0);
}
td {
padding-right:10px;
padding-left:10px;
border: 10px;
}
</style>
<body>
<button class="tableRevmoveButton"> Remove table </button>
<button class="tableAddButton"> Add table </button>
<button class="tableAddNewButton"> Add different table </button>
<div class="tabel">
<table class="itdev_people">
<tr class="header-class">
<td colspan="4">The Blips</td>
</tr>
<tr class="members blips">
<td>Rotton </td>
<td>Rob</td>
<td>ttt</td>
</tr>
<tr class="members blips">
<td>Effram</td>
<td>The Dumb Rabbot</td>
</tr>
<tr class="members blips">
<td>Effram</td>
<td>The Dumb Rabbot</td>
</tr>
<tr class="header-class">
<td colspan="2">The Crudz</td>
</tr>
<tr class="members crudz">
<td>Jason</td>
<td>"Sky" Halker</td>
</tr>
<tr class="members crudz">
<td>Sparky</td>
<td>That stupid Eagle</td>
</tr>
<tr class="header-class">
<td colspan="2">The Satin Flings</td>
</tr>
<tr class="members satin-flings">
<td>Josh-man</td>
<td>McDanielson-man III</td>
</tr>
<tr class="members satin-flings">
<td>Dominque</td>
<td>The Christmas Donkey</td>
</tr>
<tr class="header-class">
<td colspan="2">The Satin Flings</td>
</tr>
<tr class="members satin-flings">
<td>Josh-man</td>
<td>McDanielson-man III</td>
</tr>
<tr class="members satin-flings">
<td>Dominque</td>
<td>The Christmas Donkey</td>
</tr>
</table>
</div>
<script>
//Table action
$('.header-class').click(function() {
console.log('clicked');
if ($(this).hasClass('collapsed')) {
$(this)
.nextUntil('tr.header-class')
.find('td')
.parent()
.find('td > div')
.slideDown('fast', function() {
var $set = $(this);
$set.replaceWith($set.contents());
});
$(this).removeClass('collapsed');
} else {
$(this)
.nextUntil('tr.header-class')
.find('td')
.wrapInner('<div style="display: block;" />')
.parent()
.find('td > div')
.slideUp('fast');
$(this).addClass('collapsed');
}
});
//Table Remove Button action
$('.tableRevmoveButton').click(function() {
$('.tabel').remove();
console.log('Remove table');
});
//Table add Button action für add
$('.tableAddButton').click(function() {
$('body').append('.tabel');
console.log('Add table');
});
</script>
</body>
</html>
if you have class for table which i guess you are having .tabel then use this
$('.tableAddButton').click(function() {
$('body').addClass('.tabel');
console.log('Add table');
});
but if dont have a class and want to create table with html code in script then
$('.tableAddButton').click(function() {
$('body').append('<table><thead>...</thead>...</table>');
console.log('Add table');
});
or if you want only table in the body
$('.tableAddButton').click(function() {
$('body').html('<table><thead>...</thead>...</table>');
console.log('Add table');
});
It shouldn't be too difficult using the .append() JQuery function. When the button is clicked, select the tableDiv that you want to add the new table to, and then append table html.
$("#btn").click(function(){
$("#tableDiv").append("<table><tr><th>Appended table</th></tr></table>");
});

Get ID of Table that contains a checkbox

I have many tables each one with an ID, (table1,2,3,...), and in each one I have many TD's <td><a href
example :
<table id="myTable1" class="someclass">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
<table id="myTable2" class="someclasse">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
(don't look at the HTML code it's not important for now )
My goal is to open all hrefs within the table "table X" then open them in new tab. I do that with
var els = document.getElementById("myTable1").querySelectorAll("a[href^='https://domaine.']");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
alert(el)
window.open (el,"_blank");
}
It works like a charm. Now I want to add a checkbox to each table, and if checked to open the href on "the" table I checked (I did some innerHTML to "insert" checkbox). Now my question, how can I get the table ID when I'll check the checkbox?
For example I check the table that have "table6" and then every link in that table gets opened.
table id=1 (checkbox)
table id=2 (checkbox)
etc
if i check the checkbox it will get the table with id 2
You can use closest to get the closest table, then you can get the id from that.
// List of checkboxes
let inputs = Array.from(document.querySelectorAll('input[type=checkbox]'))
// Add a click event to each
inputs.forEach(input => {
input.addEventListener('click', e => {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
})
})
<table id="abc">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="def">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="ghi">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="jkl">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
You say that you are adding the checkbox dynamically, so you won't want to do a querySelectorAll like I did above. You will want to add it when it is created like this:
// List of tables
let tables = Array.from(document.querySelectorAll('table'))
// insert the checkbox dynamically
tables.forEach(table => {
table.innerHTML = '<tr><td><input type="checkbox"></td></tr>'
// Get the checkbox
let checkbox = table.querySelector('input[type=checkbox]')
// Add an eventlistener to the checkbox
checkbox.addEventListener('click', click)
})
function click(e) {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
}
<table id="abc">
</table>
<table id="def">
</table>
<table id="ghi">
</table>
<table id="jkl">
</table>
…I want to add a checkbox to each table, and if [it's] checked…open the href [in] "the" table I checked…how can I get the table ID when I'll check the checkbox?
Given that you want to find the id of the <table> within which the check-box <input> is contained in order to select the <table> via its id property you don't need the id; you simply need to find the correct <table>.
To that end I'd suggest placing an event-listener on each of those <table> elements, and opening the relevant links found within. For example (bearing in mind that there are restrictions on opening new windows/tabs on Stack Overflow, I'll simply style the relevant <a> elements rather than opening them):
function highlight(e) {
// here we find the Static NodeList of <a> elements
// contained within the <table> element (the 'this'
// passed from EventTarget.addEventListener()) and
// convert that Array-like collection to an Array
// with Array.from():
Array.from(this.querySelectorAll('a'))
// iterating over the Array of <a> elements using
// Array.prototype.forEach() along with an Arrow
// function:
.forEach(
// here we toggle the 'ifCheckboxChecked' class-name
// via the Element.classList API, adding the class-name
// if the Event.target (the changed check-box, derived
// from the event Object passed to the function from the
// EventTarget.addEventListener function) is checked:
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
// converting the Array-like Static NodeList returned
// from document.querySelectorAll() into an Array:
Array.from(document.querySelectorAll('table'))
// iterating over the Array of <table> elements:
.forEach(
// using an Arrow function to pass a reference to the
// current <table> element (from the Array of <table>
// elements to the anonymous function, in which we
// add an event-listener for the 'change' event and
// bind the named highlight() function as the event-
// handler for that event:
table => table.addEventListener('change', highlight)
);
function highlight(e) {
Array.from(this.querySelectorAll('a'))
.forEach(
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
Array.from(document.querySelectorAll('table')).forEach(
table => table.addEventListener('change', highlight)
);
body {
counter-reset: tableCount;
}
table {
width: 80%;
margin: 0 auto 1em auto;
border: 1px solid limegreen;
}
table::before {
counter-increment: tableCount;
content: 'table' counter(tableCount);
}
a.ifCheckboxChecked {
background-color: #f90;
}
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
JS Fiddle demo.
References:
CSS:
::before pseudo-element
Using CSS Counters.
JavaScript:
Array.from().
Array.prototype.forEach().
Arrow Functions.
Element.querySelectorAll().
Event.
EventTarget.addEventListener().

Unable to get data from the second column of a table on clicking of the button in third column

I have a table which has four columns second being a paragraph field , the third being an input field and fourth being a button . What i want is on clicking of the button row the data from the paragraph column should be applied to the input field i.e third row .
Its not possible to select every row using each function as every row is different and theres only few rows like this . How can this be done
I have tried this but it didn't work
var or1 = $("#tab_logic button");
or1.each(function() {
$(this).click(function(){
alert("u");
var u = $(this).parent("tr").find('td:first').html();
alert(u);
});
});
Without knowing the exact HTML, I made this based on your explanation. If I understand correctly, this is what you want to achieve?
$("button").click(function() {
var row = $(this).closest("tr");
var name = row.find("p").html();
var input = row.find("input");
input.val(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Input</th>
<th>Button</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><p>John Doe</p></td>
<td><input type="text" placeholder="Name"/></td>
<td><button type="button">Set name</button></td>
</tr>
<tr>
<td>1</td>
<td><p>Jane Doe</p></td>
<td><input type="text" placeholder="Name"/></td>
<td><button type="button">Set name</button></td>
</tr>
</tbody>
</table>
Another solution would be
var or1 = $("#tab_logic button");
or1.each(function() {
$(this).click(function() {
var text = $(this).closest('tr').children('td:eq(1)').children().first().html();
$(this).closest('tr').children('td:eq(2)').children().first().val(text);
});
});
#tab_logic td{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tab_logic">
<tr>
<td>one</td>
<td><p>I'm just a paragraph</p></td>
<td><input type="text"/></td>
<td><button>button</button></td>
</tr>
<tr>
<td>two</td>
<td><p>I'm just another paragraph</p></td>
<td><input type="text"/></td>
<td><button>button</button></td>
</tr>
</table>

Categories