I have a table with 3 rows, each having hrefs. On click of these links, i need to get the entire value of the row where the link is clicked.
Data
Test1_link image_link view-link
Test2_link image_link view-link
the data above are links, on click on any link, its corresponding row value should be rendered.
Can anyone please suggest me on how to achieve that?
Thanks.
You could put a simple script immediately after your table:
<script>
(function (d) {
// Get the table element
var table = function() {
var tables = d.getElementsByTagName('table');
return tables[tables.length - 1];
}();
table.onclick = function (e) {
var target = e.target;
// If an <a> was clicked
if( target.nodeName.toLowerCase() === 'a' ) {
// Find the tr containing that a
var node = target;
while (node.nodeName.toLowerCase() !== 'tr' )
node = node.parentNode;
var tr = node;
// Output the contents of the table cells in that row
var cells = tr.cells;
for (var i = 0; i < cells.length; i++ )
console.log(cells[i].innerHTML);
// Return false to prevent the link from loading
return false;
}
}
})(document)
</script>
JSFiddle
Try this with jQuery http://www.jquery.com.
<table class="js-mytable">
<tr data-id="23" data-something="you've got it!">
<td>
Test Link
</td>
<td>
Image Link
</td>
<td>
View Link
</td>
</tr>
</table>
<script>
//run after document ready event
$(function(){
//all links in table with class js-mytable
$('table.js-mytable').on('click','a',function(){
//var $cell = $(this).parents('td'); //get the parent td of the link
var $row = $(this).parents('tr'); //get the parent tr of the link
//get the html5 data attributes from the row
var id = $row.data('id');
var something = $row.data('something');
//do something with the vars
//alert('Id: '+id+': '+something);
//get the full html <tr>...</tr>
//we need to merge it to a new pseudo html element
//to get the full html with surrounding <tr>
var html = $('<div>').append($row.clone()).html();
alert(html);
return false; //prevent default link action (href)
});
});
</script>
If you need more details, you need to extend your question...
JsFiddle: http://jsfiddle.net/7ud43
Related
I have an HTML document with 6 Divs, I've written a javascript code that changes the heading depending on which div is selected (6 vars and 6 functions) e.g.
var divSelect = document.getElementById("firstDiv");
divSelect.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected the first option";
};
I then have an anchor div which is linking to another HTML page, when it opens I want it to know which div was selected from the first HTML page, and then input a new heading based on the selection.
So I need to know which of the six functions was actioned based on the div that was clicked.
Any help much appreciated.
You can pass it in url query. Passing for example id parameter, like this: http://example.com/secondpage.html?firstpagedivid=firstDiv And then on second page you can parse url to get div id or whatever parameter you passed.
Here you can find how to get url parameter on second page: link
Html:
<div class="clickable" id="firstDiv">first</div>
<div class="clickable" id="secondDiv">second</div>
<div class="clickable" id="thirdDiv">third</div>
<br>
<div id="heading"></div>
<br>
<a id="navigator" href="second.html">Next page</a>
Javascript:
(function() {
var currentSelectedDiv;
var heading = document.getElementById('heading');
var navigator = document.getElementById('navigator');
var divs = document.querySelectorAll('.clickable');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function(e) {
var target = e.target;
currentSelectedDiv = target.getAttribute('id');
heading.innerHTML = ['You have selected ', currentSelectedDiv].join('');
}
}
navigator.onclick = function(e) {
e.preventDefault();
var a = e.target;
var href = a.getAttribute('href');
href += '?previousPageDivId=' + currentSelectedDiv;
alert(href);
//Just uncomment line below
//document.location.href = href;
}
})();
Here you have working example: https://jsfiddle.net/3wdzh2d4/
I have the following code which is supposed to generate rows in a table where each row has its own content and delete button.
<!DOCTYPE html>
<html>
<head>
<title>table</title>
</head>
<body>
<input id="inputText">
<button onclick = "addRow()">Add text</button>
<table id = "table">
</table>
<script>
function addRow(){
var newRow = document.createElement("tr");
var col1 = document.createElement("td");
var col2 = document.createElement("td");
newRow.appendChild(col1);
newRow.appendChild(col2);
var button = document.createElement("button");
button.innerHTML = "delete";
button.onclick = function () {
var index = this.parentNode.parentNode.rowIndex;
document.getElementById("table").deleteRow(index);
}
col1.appendChild(button);
var enteredText = document.getElementById("inputText").value;
col2.innerHTML = enteredText;
document.getElementById("table").appendChild(newRow);
}
</script>
</body>
</html>
The problem is that no matter which delete button I press, it deletes the last row.
I tried using console.log(this.parentNode.parentNode) to see if it returns the right <tr> object, and it indeed does. But for some reason, the attribute rowIndex is -1 no matter what button is pressed; hence only the last row is deleted. Does it mean that each dynamically generated <tr> doesn't know its row index?
You can use HTMLTableElement.insertRow() function instead.
var newRow = document.getElementById("table").insertRow();
// newRow.rowIndex will return you the proper index
Here is a working fiddle
Update
It was a bug in the Webkit layout engine, (that moved to the forked Blink engine as well). This is why it works well in Firefox but not in earlier versions of Chrome (Blink) or Safari (Webkit).
The bug report is here, it's fixed now.
There are numerous way to achieve what you require. Here is another such example that is based on the code that you posted. Hopefully it will give you some further ideas.
(function() {
// create references to static elements, no need to search for them each time
var inputText = document.getElementById("inputText"),
butAdd = document.getElementById("butAdd"),
table = document.getElementById("table");
// a generic function for finding the first parent node, starting at the given node and
// of a given tag type. Retuns document if not found.
function findParent(startNode, tagName) {
var currentNode,
searchTag;
// check we were provided with a node otherwise set the return to document
if (startNode && startNode.nodeType) {
currentNode = startNode;
} else {
currentNode = document;
}
// check we were provided with a string to compare against the tagName of the nodes
if (typeof tagName === 'string') {
searchTag = tagName.toLowerCase();
} else {
currentNode = document;
}
// Keep searching until we find a parent with a mathing tagName or until we get to document
while (currentNode !== document && currentNode.tagName.toLowerCase() !== searchTag) {
currentNode = currentNode.parentNode;
}
// return the match or document
return currentNode;
}
// for deleting the current row in which delete was clicked
function deleteRow(e) {
// find the parent with the matching tagName
var parentTr = findParent(e.target, 'tr');
// did we find it?
if (parentTr !== document) {
// remove it
parentTr.parentNode.removeChild(parentTr);
}
}
// for adding a row to the end of the table
function addRow() {
// create the required elements
var newRow = document.createElement("tr"),
col1 = document.createElement("td"),
col2 = document.createElement("td"),
button = document.createElement("button");
// add some text to the new button
button.appendChild(document.createTextNode("delete"));
// add a click event listener to the delete button
button.addEventListener('click', deleteRow, false);
// append all the required elements
col1.appendChild(button);
col2.appendChild(document.createTextNode(inputText.value));
newRow.appendChild(col1);
newRow.appendChild(col2);
// finally append all the elements to the document
table.appendChild(newRow);
}
// add click event listener to the static Add text button
butAdd.addEventListener('click', addRow, false);
}());
<input id="inputText">
<button id="butAdd">Add text</button>
<table id="table"></table>
i have been read alotof article about each(function(){ .... to get values html tablee childs. But i can not do that. i would like you help me. My some bad experiments are not working.There is a outside a button which is not in rows. While clicking a button, row values must return me.I need td's span values...
My not working samples: NOT WORKING:
var id = $("#listsends").closest("tr").find(".label label-warning").text();
NOT WORKING :
alert(id);
$("#listsends").find('.label label-warning').each(function () {
var textval = $('.label label-warning').text(); // this will be the text of each <td>
alert(textval);
});
var t = $('.label label-warning');
for (var i = 0; i < t.length; i++)
alert(t[i].text());
By clicking web button(outside of table, not inside) , tables's td ^s span values:
$("#listsends").find('.label label-warning').each(function () {
var textval = $(this).text(); // as this is the scope of the element
alert(textval);
});
How can you get the id of a table when you click an input element?
I don't need the rowId etc.
I've tried parentNode.id but I can't seem to get the id.
In the end I'd like to do something like this:
var tabelid = INPUT....parentNode.parentNode.id;
var table = document.getElementById(tabelid);
Example:
How about this:-
Demo
Html
<table id="tblTest">
<tr>
<td>
<input type="text" id="txtTest" onclick="getParent.call(this)" />
</td>
</tr>
</table>
I am using call here so that i get the elements context inside the getParent event callback.
Javascript
function getParent()
{
var parent = this.parentNode;
var tagName = "table";
while (parent) { //Loop through until you find the desired parent tag name
if (parent.tagName && parent .tagName.toLowerCase() == tagName) {
alert(parent .id);
return;
}
else
{
parent = parent .parentNode;
}
}
}
If you are using Jquery:-
in the click event you can just do $(this).closest('table').attr('id')
If you are using jQuery you can use closest to find the closest matching ancestor like so:
var tableID = "";
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').attr('id');
});
]);
Edit:
If you actually want to do something with that table (for instance add a class), you could do the following:
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').addClass('myClass');
});
]);
This simply removes the need to fetch the table ID, store it, and then fetch the table based on it's ID. Since you already found the table in order to get its ID you can just manipulate it right away.
You have to ascend the DOM from TD to TABLE keeping in mind that browsers may inject a TBODY if you haven't specified it. So, your code should look something like this:
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,
i;
for (i = 0; i < cellCount; i += 1) {
tableCells[i].onclick = function () {
var tableId = getTableId(this);
console.log(tableId);
};
}
function getTableId(node) {
var element = node;
while (element.tagName.toLowerCase() !== 'table') {
element = element.parentNode;
}
return element.id;
}
Check out the demo.
I'd like to do a small function that would permute 2 cells of a table with jQuery (or PHP/Ajax).
Let's say I have the following table:
<table class="table">
<tr>
<td class="btn" data-cellN="1">
01
</td>
<td class="btn" data-cellN="2">
02
</td>
</tr>
<tr>
<td class="btn" data-cellN="3">
05
</td>
<td class="btn" data-cellN="4">
06
</td>
</tr>
</table>
How to select 2 cells and permute them?
EDIT:
I made my way through the function thanks to your advice, nevertheless. It is working the first time bug I got a weird bug coming from the c1 c2 c3 variables, I don't know why,
could anyone help me to finish my function please?
Here is my Javascript: (it is wrapped in a doc ready)
var nbbuttonclicked=0; // to trigger the movecell function after the second button was clicked
var count=0; //Number of tinme we moved a cell
var table = {
c1:null,
c2:null,
c3:null,
check: function(){
$('td').on('click', function(){ //When the user click on a button we verify if he already clicked on this button
if( $(this).hasClass('btn-info') ) {
//If yes, then remove the class and variable c1
$(this).removeClass('btn-info');
table.c1=0;
nbbuttonclicked--;
}else{
//if no, then add a class to show him it is clicked and remember the value of the cell
$(this).addClass('btn-info');
if( typeof table.c1 === 'undefined' || table.c1===null) {
table.c1 = $(this);
console.log('c1:'+table.c1.html());
}else{
table.c2 = $(this);
console.log('c2:'+table.c2.html());
}
nbbuttonclicked++;
if( nbbuttonclicked==2 ) {
table.movecell(table.c1,table.c2); // we trigger the function to permute the values
}
}
});
},
movecell: function(c1, c2){
//We reset that variable for the next move
nbbuttonclicked=0;
//we move the cells
table.c3=c1.html();
c1.html(c2.html());
c2.html(table.c3)
c1.removeClass('btn-info');
c2.removeClass('btn-info');
table.c1=table.c2=table.c3=c1=c2=null;
},
// movecell: function(c1, c2){
// We check if the cells.html() are = to data-cellN. If yes, you won
// foreach()
// },
// var row = $('table tr:nth-child(1)')[0];
// moveCell(row, 0, 3);
};
table.check();
and here is a sample:
http://jsbin.com/exesof/2/edit
Try this code:
var cell0,
cell1,
next,
row0,
row1;
$('td').on('click', function() {
if(!cell0) {
cell0 = this;
row0 = cell0.parentNode;
return;
} else if(!cell1) {
cell1 = this;
row1 = cell1.parentNode;
// === Switch cells ===
next = cell0.nextSibling;
row1.insertBefore(cell0, cell1);
row0.insertBefore(cell1, next);
// ====================
row0 = row1 = cell0 = cell1 = next = null;
}
});
Working example you can try here: http://jsbin.com/irapeb/3/edit
Click one of the cells, than another one and see they are switched :)
This code will move the 4th td (referenced as cell[3]) on place of the first cell (cell[0]) in the first row (and the 1st becomes the 4th):
function moveCell(row, c1, c2) {
var cell = row.cells;
arr = [c1, c2].sort(),
c1 = arr[1],
c2 = arr[0];
row.insertBefore(row.insertBefore(cell[c1], cell[c2]).nextSibling, cell[c1].nextSibling);
}
var row = $('table tr:nth-child(1)')[0];
moveCell(row, 0, 3);
http://jsfiddle.net/2N2rS/3/
I wrote this function to simplify process. It uses native table methods.
Modifying the number of row (:nth-child(1)) and indexes of the table cells you can permute them as you need.
with jQuery, you can do it with:
$(document).ready(function() {
$("table.table tbody tr td:first-child").each(function(index, element) {
// this and element is the same
$(this).insertAfter($(this).next());
});
});
Assuming you don't ommited the tbody element (which is automatically added by some browser as default behaviour)
working example
If you want to do the process when clicking on the first cell, you just have to use on with click event instead of each.
$(document).ready(function() {
$("table.table tbody tr td:first-child").on('click', function(clickEvent) {
$(this).insertAfter($(this).next());
});
});
This can be done in pure javascript:
Fetch clicked sell count;
Fetch data of both cells, when they are selected;
Replace cell values with the opposite ones;
Store new values in DB via ajax call.
Now it's up to you to write the script.