i am passing a very hard time with my web project.because i am new with web related languages.
i just want to get data of a cell by clicking the same row button of the other cell. i am adding a pic please see this first.
i try with many codes like below---(1st try)
my js code-
var tbl = document.getElementById("myTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].cells[1].onclick = function (){ getval(this); };
}
}
function getval(cell) {
value(cell.innerHTML);
}
my html code
<table class="w3-table-all w3-margin-top" id="myTable">
<tr>
<th style="width:25%;">Vendor Picture Path</th>
<th style="width:25%;">Vendor Heading</th>
<th style="width:25%;">Vendor Body</th>
<th style="width:25%;">Add courses</th>
</tr>
echo '<tr>
<td>'.$row["pic_path"].'</td>
<td style="cursor: pointer;color:red;">'.$row["heading"].'</td>
<td><div style="width:100%;height: 60px;margin: 0;padding: 0;overflow-y: scroll">'.$row["body"].'</div></td>
<td><button>Add</button></td>
</tr>';
my table data contains echo because i fatch the table data from my sql server.
my second try...
js code
var tb2=document.getElementById("myTable");
if(tb2 != null)
{
for(h=0;h<tb2.rows.length;h++)
{
bf=tb2.rows[h].cells[1];
tb2.rows[h].cells[3].onclick=function(){getbtval(bf);};
}
}
function getbtval(cell)
{
alert(cell.innerHTML);
}
and html code same...
1st one work for me.but that was not my expected result.
my code success on second one result.but that fails.when i click every add button it gives me just the last value of 2nd cell last row and that is "ORACLE".
PLEASE TELL ME WHAT IS WRONG WITH MY CODE......
Problem with your code is the fact you are not binding events to the button, you are picking a random cell of the table row. And the other issue is the fact you are not using var so it makes things global.
You said you want to click the button, but your code is not selecting the button. So instead of adding events all over the place, just use one and let event delegation take care of it. Check to see what triggered the event. If it is a button, than select the row and than you can read the text of the cells.
document.getElementById("myTable").addEventListener("click", function(evt) {
var btn = evt.target;
if(btn.tagName==="BUTTON"){
var row = btn.parentNode.parentNode; //td than tr
var cells = row.getElementsByTagName("td"); //cells
console.log(cells[0].textContent, cells[1].textContent);
}
});
<table class="w3-table-all w3-margin-top" id="myTable">
<tr>
<th style="width:25%;">Vendor Picture Path</th>
<th style="width:25%;">Vendor Heading</th>
<th style="width:25%;">Vendor Body</th>
<th style="width:25%;">Add courses</th>
</tr>
<tr>
<td>123</td>
<td style="cursor: pointer;color:red;">YYYY</td>
<td>
<div style="width:100%;height: 60px;margin: 0;padding: 0;overflow-y: scroll">XXX</div>
</td>
<td>
<button>Add</button>
</td>
</tr>
<tr>
<td>456</td>
<td style="cursor: pointer;color:red;">dasdas</td>
<td>
<div style="width:100%;height: 60px;margin: 0;padding: 0;overflow-y: scroll">qwwqeqwe</div>
</td>
<td>
<button>Add</button>
</td>
</tr>
</table>
cell.onclick = function (){ getval(this); };
this means "current context", that is the cell which produced the click event.
bf=tb2.rows[h].cells[1];
tb2.rows[h].cells[3].onclick=function(){getbtval(bf);};
After the for loop, bf points to the cell in the last row, so getval(bf) returns the value of it.
To access the proper cell, do the DOM traversal as #epascarello suggests. Depending on your use-case, it also might be easier to use data attribute:
<button data-value="Cisco">
And then in the JS code
button.onclick = function() { alert(this.dataset.value); }
You need to first identify the row clicked, for this you can check which element is current clicked by adding an event listener on the entire table and check when the target is button.
Once you get the event target as button , find its parent td and its parent tr.
Now you got the tr and just loop through the child nodes, exclude the nodeType == 3 so that you only get the td element in the tr
document.getElementById("myTable").addEventListener("click",function(e){
e = e || event
var target = e.target || e.srcElement;
if (target.nodeName != 'BUTTON') return
var row = target.parentNode.parentNode;
row.childNodes.forEach(function(item){
if(item.nodeType !== 3)
{
console.log(item.textContent);
console.log(item.innerHTML);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="w3-table-all w3-margin-top" id="myTable">
<tr>
<th style="width:25%;">Vendor Picture Path</th>
<th style="width:25%;">Vendor Heading</th>
<th style="width:25%;">Vendor Body</th>
<th style="width:25%;">Add courses</th>
</tr>
<tr>
<td>cisco-networking.jpg</td>
<td style="cursor: pointer;color:red;">CISCO</td>
<td><div style="width:100%;height: 60px;margin: 0;padding: 0;overflow-y: scroll">CISCO systems</div></td>
<td><button>Add</button></td>
</tr>
</table>
I've done this by assigning the td an id and grabbing the text using jquery
Related
I am implementing the IGV genome browser in a website.
I would like to link a table with chromosome positions to the genome browser, so when a user clicks to one position, the genome browser changes to that position automatically.
By now, I have the genome browser code in a separate javascript file, which uses the value of the button.
// Construct genome browser
document.addEventListener("DOMContentLoaded", function () {
// Obtain position
var position = $('#ins').val();
// Use the position
var options = {locus: position, ...};
var igvDiv = document.getElementById("igvDiv");
igv.createBrowser(igvDiv, options)
.then(function (browser) {
console.log("Created IGV browser");
})
};
And the table in html with buttons.
<table class='results-table'>
<tr>
<th class='text text--bold'>Chromosome</th>
<th class='text text--bold'>Start</th>
<th class='text text--bold'>End</th>
<th class='text text--bold'>Genome Browser</th>
</tr>
<tr>
<td class='text'>chr1</td>
<td class='text'>0</td>
<td class='text'>100</td>
<td><button class='editbtn' value='chr1:0-100' id='ins1'>chr1:0-100</button></td>
</tr>
<tr>
<td class='text'>chr2</td>
<td class='text'>200</td>
<td class='text'>400</td>
<td><button class='editbtn' value='chr2:200-400' id='ins2'>chr2:200-400</button></td>
</tr>
</table>
With this, the browser gets the first position but it does not change when I click the button.
I think I need some kind of onClick() action but I can't figure out how to change a javascript script.
Any help would be appreciated.
Thank you!
Júlia
edit:
I added more javascript code as I think that I was not able to illustrate my question properly. And also modified the ids from buttons, to make them different.
The question is how to use different ids in javascript depending on the button that was clicked.
You can change some things. I remove the id from your buttons because you will already have the context with the passing event. And instead of a value in the button, I would recommend you to use a data attribute. data-value for example.
function check(e) {
console.log(e.getAttribute('data-value'))
}
<button class='editbtn' onclick="check(this)" data-value='chr2:200-400' >chr2:200-400</button>
<button class='editbtn' onclick="check(this)" data-value='chr1:0-100' >chr1:0-100</button>
You can access the ID and value in a click event:
// Construct genome browser
document.querySelector('table.results-table').addEventListener('click', function ({ target }) {
if (!target.id) return;
const id = target.id;
const position = target.value;
console.log(id);
console.log(position);
});
<table class='results-table'>
<tr>
<th class='text text--bold'>Chromosome</th>
<th class='text text--bold'>Start</th>
<th class='text text--bold'>End</th>
<th class='text text--bold'>Genome Browser</th>
</tr>
<tr>
<td class='text'>chr1</td>
<td class='text'>0</td>
<td class='text'>100</td>
<td><button class='editbtn' value='chr1:0-100' id='ins1'>chr1:0-100</button></td>
</tr>
<tr>
<td class='text'>chr2</td>
<td class='text'>200</td>
<td class='text'>400</td>
<td><button class='editbtn' value='chr2:200-400' id='ins2'>chr2:200-400</button></td>
</tr>
</table>
The table being made dynamically using Thymeleaf. Each row of the table has a img link attached to it. On the click of which I want to get the selected rows img link first , second and third cell.
Relevant Table Code
<table class="table" id="tblDocType" style="padding: 20px 10px;">
<thead class="thead-dark">
<tr>
<th scope="col"> <b> Document Type </b></th>
<th scope="col"> <b> Practice Area </b> </th>
<th scope="col"><b> Retention Policy </b></th>
<th scope="col"> <b> Effective Date<br> Required </b></th>
<th scope="col"> <b> Termination Date<br> Required </b></th>
<th scope="col"> <b> Action</b></th>
</tr>
</thead>
<tr th:each="doctype,iterStat : ${dlist}">
<td th:text = "${doctype?.doctypes}"></td>
<td th:text = "${doctype?.practiceAreaId}"></td>
<td th:text = "${doctype?.retention_policy}"></td>
<td th:text = "${doctype?.effectiveDateRequired}"></td>
<td th:text = "${doctype?.terminationDateRequired}"></td>
<td>
<a href="#" th:name="${doctype?.practiceAreaId}" th:id="${iterStat.index}" onclick="deleteTrigger(this.id)" style="color: blue;">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
</table>
I am trying to get the cell values using jquery.
Relevant jquery code
function deleteTrigger(id){
var value=$("#tblDocType").closest("tr").find('td:eq(0)').text();
console.log("value=",value);
var doctypesjson={
"doctypes": id,
"practiceAreaId": pracaticeareaidfrombutton
};
}
In the console the value is coming blank.
Please help me if you know what can be done for the problem. Thank you in advance
Presently, it appears that your code is looking for the first TR, then within that the first TD. However, this won’t do anything as your first TR only contains TH.
In calling your deleteTrigger() function, you should pass through the element that was clicked
deleteTrigger(this); // use this for your TR lookup.
However, since you’re using jQuery already, it may make your life easier to abandon the delete function altogether and use a listener;
$(“tr”).click(function(){
$(this).find(“td”).first() // this will get the first td of a clicked row
$(this).find(“td”).eq(1) // this will get second td etc...
})
I'm using html5 and jquery to set up a dynamic table, until then I can add the elements to the table without problems, but I can not retrieve the value of its columns. so I have the following questions:
How can I recover the table data by clicking the ROW?
Should I always use the data-name, id for example as in the first
line ?
$(document).on("change", "#TabClientesAdicionados", function(e) {
alert('?');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
How can I recover the table data by clicking the ROW?
You can bind the click event to your TR elements and get the information.
Should I always use the data-name, id for example as in the first line?
Yes, because you don't want the parsed HTML to manipulate data. The data attributes are a better approach to keep related data (no HTML) to DOM elements.
Look at this code snippet
This approach binds the click event to TR elements
$('#TabClientesAdicionados tbody tr').click(function() {
var data = { name: '', id: '' };
$(this).children('td').each(function() {
var name = $(this).data('nome');
if (name) {
data.name = name;
}
var id = $(this).data('id');
if (id) {
data.id = id;
}
});
console.log(data);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno_1">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
I would do as the following snippet.
You need to bind the event to the row tr ant then get each of its children.
By adding a data attribute you could set a column name. This could also help if you eventually needed to extract the value of an specific cell.
Incidentally you could also add a second data attribute named like data-value or something similar- This in case you are worried that your parsed html content might cause you trouble with the values.
$(document).ready(function() {
$("#mytable").on('click', 'tr', onCellClick);
//Bind the event to the table row
function onCellClick() {
let row = $(this); //get the jquery Object for the row
let rowValues = {}; //An empty object to hold your data
let temp;
//extract the value of every cell in the row
//Doing it this way gives you flexibility on the amount of colums you have
row.find('td').each(function(item) {
temp = $(this);
rowValues[temp.data('column')] = temp.text();
//this could be changed to
//rowValues[temp.data('column')] = temp.data('value);
//if you desire to use a separate data-value property
});
console.log(rowValues);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%" id="mytable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td data-column="name" data-value="Jill">Jill</td> <!-Adding value property-->
<td data-column="lastname">Smith</td>
<td data-column="age">50</td>
</tr>
<tr>
<td data-column="name">Eve</td>
<td data-column="lastname">Jackson</td>
<td data-column="age">94</td>
</tr>
</table>
I have a table that are like a grid with a horizontal list in the top with week numbers within th tags and below each week are different values in rows of tr and td tags.
I'm trying to get the data-attribute for the week when I click below in one of the td tags with the data-id attribute. But I can't get it right and wonder what I have done wrong to be able to read this value?
Some of the combinations I have tested:
var test = $(this).closest("th").attr("data-week");
var test = $(this).parents().find(".week").attr("data-week");
var test = $(this).parents("th").attr("data-week");
The HTML with data-attributes for the table:
<table>
<thead>
<tr>
<th class=""></th>
<th class="week" data-week="15">15</th>
<th class="week" data-week="16">16</th>
<th class="week" data-week="17">17</th>
<th class="week" data-week="18">18</th>
<th class="week" data-week="19">19</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stina (1)</td>
<td data-id="40">10</td>
<td data-id="12">20</td>
<td data-id="13">40</td>
<td data-id="14">45</td>
<td data-id="15">40</td>
</tr>
<tr>
<td>Linda (2)</td>
<td data-id="0">0</td>
<td data-id="0">0</td>
</tr>
<tr>
<td>Lasse (3)</td>
<td data-id="21">5</td>
<td data-id="22">39</td>
<td data-id="23">40</td>
<td data-id="24">40</td>
</tr>
</tbody>
</table>
#Sean DiSanti, good one!
Here is a slightly more efficient version, without warping $ in $, by using eq method
$('td').on('click', function(e) {
var index = $(this).index() -1;
var week = $('.week').eq(index).data('week');
console.log('week', week);
});
jsfiddle
Here is a way you can find the data-week attribute of the clicked th element.
$(document).ready(function(){
$("td").on("click",function(){
$td=$(this);
$th = $td.closest('table').find('th').eq($td.index());
alert($th.attr("data-week"));
});
});
Demo: https://jsfiddle.net/7b146hor/2/
You need to find it by index. Get which child number the clicked element has and then look for same number in .weeks
Demo
$('td').on('click', function(e){
index = $(this).index();
week = $('.weeks').find(":eq("+index+")").attr('data-week');
console.log(week);
});
This worked for me
$('td').on('click', function(e) {
index = $(this).index();
week = $($('.week')[index - 1]).data('week');
console.log('week', week);
});
jsfiddle example
I am making a form to add players into an event.
The form searches a db of players with search criteria specified by the user and then lists all matching players with an add button next to them.
I also have a table with all the table headers done and then a
<div id="PlayerAdded">
tag before the end of the table.
I have written a function to output the data for the next row to the table when a players "Add" button is clicked. My function says:
function add(){
document.getElementById("PlayerAdded").innerHTML += "<tr><td>success</td></tr>";
}
I expected this to add a row, but instead it adds just the word "success" above the table (Perhaps I was a little optimistic when I used the word success as my test string lol).
Can someone please tell me why it is not adding the code inside the div "PlayerAdded"?
If it helps, here is some of the HTML:
<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?></th></tr>
<tr><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th></tr>
<div id="PlayerAdded"> </div>
<tr><td colspan='3'>Search <input type='text' id='newsearch'></input>
</table>
There were a couple of problems with your existing HTML - which therefore broke your DOM when the browser attempted to assemble things.
a <div> element – in a <table> – must be contained within either a <th> or <td> element; no other element is a valid child of a <tr> element, and the only valid children of a <table> element are <thead>, <tfoot>, <tbody> and <tr> elements.
neither your last <tr>, or its child <td>, element were closed – the browser will automatically close these elements when it encounters another <td> (since neither a <td>, nor a <tr>, can be directly nested within another <td>).
That said, I'd correct your HTML to the following:
<table>
<tbody>
<tr>
<th colspan='6'>« php response »</th>
</tr>
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr>
<td colspan='3'>Search
<input type='text' id='newsearch' />
</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNewRow">Add a new row</button>
And your JavaScript to the following:
function addNewRow() {
// creating the relevant elements to be added:
var row = document.createElement('tr'),
td = document.createElement('td');
// setting the text of the created-<td> element:
td.textContent = 'Success';
// setting the colSpan property (the colspan attribute):
td.colSpan = '6';
// adding a class-name to the created-<td>, to make it
// visually obvious which are the newly-added <td>
// elements:
td.classList.add('addedRow');
// appending the created-<td> to the created-<tr>:
row.appendChild(td);
// finding the last <tr> of the table, using
// document.querySelector() which will match
// only the first element that matches the
// supplied CSS selector (or null, if no
// element exists that matches):
var lastRow = document.querySelector('table tr:last-child');
// inserting the created-<tr> (and its descendant
// elements parentNode of the lastRow node before
// the lastRow node):
lastRow.parentNode.insertBefore(row, lastRow);
}
// using unobtrusive JavaScript to add the 'click'
// event-listener to the <button> element with the
// id of 'addNewRow':
document.getElementById('addNewRow').addEventListener('click', addNewRow);
function addNewRow() {
var row = document.createElement('tr'),
td = document.createElement('td');
td.textContent = 'Success';
td.colSpan = '6';
td.classList.add('addedRow');
row.appendChild(td);
var lastRow = document.querySelector('table tr:last-child');
lastRow.parentNode.insertBefore(row, lastRow);
}
document.getElementById('addNewRow').addEventListener('click', addNewRow);
table,
td,
th {
border: 1px solid #000;
min-height: 2em;
}
td.addedRow {
font-weight: bold;
text-align: center;
border-color: limegreen;
}
<table>
<tbody>
<tr>
<th colspan='6'>« php response »</th>
</tr>
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr>
<td colspan='3'>Search
<input type='text' id='newsearch' />
</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNewRow">Add a new row</button>
External JS Fiddle demo, for experimentation or development.
References:
document.createElement().
document.getElementById().
document.querySelector().
Element.classList.
EventTarget.addEventListener().
Node.appendChild().
Node.insertBefore().
Try doing as user #Barmar said:
<script type="text/javascript">
function add(){
var _tr = document.createElement("tr");
var _textNode = document.createTextNode("Success");
_tr.appendChild(_textNode);
var _child = document.getElementById("botTr");
var parentDiv = _child.parentNode;
parentDiv.insertBefore(_tr, botTr);
}
</script>
And then:
<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?> </th></tr>
<tr id="topTr"><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr id="botTr"><td colspan='3'>Search <input type='text' id='newsearch' />
</table>
<input type="button" name="hitme" id="hitme" value="hitme" onclick="add();" />