jQuery: How to re-count and re-name elements - javascript

I have a list of table rows and these tr's have numbered classes for some reason (leg-1, leg-2 etc). It is already possible to delete a single tr from within this context.
After deleting a tr I need to rename the remaining tr's.
Example:
I have
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-3"></tr>
Now I delete leg-2. Remaining are:
<tr class="leg-1"></tr>
<tr class="leg-3"></tr>
Now I want to rename the remaining tr's, so that it's back to leg-1 and leg-2.
How can this be done??
Thx for any help!
EDIT:
I forgot to mention that it can have more than one tr with class "leg-1", "leg-2" ... So the right starting example would be
<tr class="leg-1"></tr>
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-3"></tr>
<tr class="leg-3"></tr>
Now when I delete leg-2 , both of the tr's with class="leg-3" have to be renamed to be class="leg-2". ..
Sorry I didn't mention this earlier!!
SEE IT IN ACTION
http://jsfiddle.net/Lynkb22n/2/

I'd suggest, at its most straightforward:
$('tr').each(function(i) {
// looking for a class-name that starts with (follows a
// word-boundary: \b) leg- followed by one or more numbers (\d+)
// followed by another word-boundary:
var matchedClass = this.className.match(/\bleg-\d+\b/);
// if a match exists:
if (matchedClass) {
// set the node's className to the same className after replacing
// the found leg-X class name with the string of 'leg-' plus the
// index of the current element in the collection plus one:
this.className = this.className.replace(matchedClass[0], 'leg-' + (i + 1));
}
});
$('tr').each(function(i) {
var matchedClass = this.className.match(/\bleg-\d+\b/);
// if a match exists:
if (matchedClass) {
this.className = this.className.replace(matchedClass[0], 'leg-' + (i + 1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="leg-2323523">
<td>1</td>
</tr>
<tr class="leg-2323523">
<td>2</td>
</tr>
<tr class="leg-2323523">
<td>3</td>
</tr>
<tr class="leg-2323523">
<td>4</td>
</tr>
</tbody>
</table>
Using an id is somewhat easier, since we don't need to preserve pre-existing concurrent ids, as we do with classes:
// selects all <tr> elements, sets their `id` property
// using the anonymous function available within prop():
$('tr').prop('id', function (i) {
// i: the index amongst the collection of <tr> elements:
return 'leg-' + (i+1);
});
$('tr').prop('id', function (i) {
return 'leg-' + (i+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</tbody>
</table>
If the index/row-number is simply to be available to JavaScript, then you could just as easily use the native rowIndex property available to all HTMLTableRowElements:
// selects <tr> elements, binds the 'mouseenter' event-handler:
$('tr').on('mouseenter', function() {
// logs the HTMLTableRowElement rowIndex property
// to the console:
console.log(this.rowIndex);
});
$('tr').on('mouseenter', function() {
console.log(this.rowIndex);
});
td {
border: 1px solid #000;
width: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</tbody>
</table>
References:
JavaScript:
HTMLTableRowElement.
JavaScript Regular Expression Guide.
String.prototype.match().
String.prototype.replace().
jQuery:
each().
prop().

Updated
Based on your comment below and your updated question, here is an updated solution.
var removed = $(".leg-2"),
siblings = removed.nextAll(), // affect only next siblings to removed element
pos = ""; // store current number after "leg-"
removed.remove(); // remove element
siblings.each(function (k) {
$(this).removeClass(function (i, key) {
pos = key.split("-")[1]; // update number after "leg-"
return (key.match(/\bleg-\S+/g) || []).join(' ');
}).addClass("leg-" + (pos - 1)); // add "leg-" plus new position
});
See it working here.
You can use .removeClass() with .match() to remove class starts with leg and then add class leg plus tr's index using .addClass().
See it working here.
$("tr").each(function (k) {
k++;
$(this).removeClass(function (i, key) {
return (key.match(/\bleg-\S+/g) || []).join(' ');
}).addClass("leg-" + k);
});

Try this it will re-name the class:
$(document).ready(function(){
$("#click").click(function(){
reorder();
});
});
function reorder(){
$('#myTable > tbody > tr').each(function(index) {
console.log($(this).attr('class','leg-'+(index+1)));//avaoid starting fron 0
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr class="leg-1"><td>a1</td></tr>
<tr class="leg-2"><td>a2</td></tr>
<tr class="leg-3"><td>a3</td></tr>
<tr class="leg-7"><td>a4</td></tr><!--after click on button class will become class="leg-4" -->
<tr class="leg-8"><td>a5</td></tr><!--after click on button class will become class="leg-5" -->
</table>
<button id="click">CliCk</button>

Related

Why does this shuffle function only work with 4+ items? JsFiddle included

I have the following code, which shuffles a set of items in the row of a table. However, the shuffle function only works when there are 4+ items:
var parent = $("#parent");
function shuffleRows(parent) {
var rows = parent.children().children(".shuffledtd1");
for (var i = rows.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = rows[i];
rows.eq(i - 1).after(rows[j]);
rows.eq(j - 1).after(temp);
}
}
shuffleRows(parent);
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<table>
<tbody id="parent">
<tr id="node2" class="shufflerow">
<td class="shuffledtd shuffledtd1">AA</td>
<td class="shuffledtd shuffledtd1">BB</td>
<!-- IF I DELETE THIS AND THE FOLLOWING ROW, THE PRIOR 2 ROWS NO LONGER SHUFFLE -->
<td class="shuffledtd shuffledtd1">CC</td>
<td class="shuffledtd shuffledtd1">DD</td>
</tr>
</tbody>
</table>
Full Code: http://jsfiddle.net/d8rkgx0z/
I think it has something to do with this portion of the code:
rows.eq(i - 1).after(rows[j]);
rows.eq(j - 1).after(temp);
but, unfortunately, my skill set simply isn't robust enough to isolate and correct the issue without hours of trial and error.
Thanks in advance for the help!
Instead of calling children twice, just pass in the direct parent of the cells. Also, shuffling the children is a lot easier using jQuery#sort:
var parent = $("#node2"); // parent should be the tr element not the tbody which is in fact a grandparent not a parent
function shuffleChildren(parent) {
parent.children() // get the children of the parent element
.sort(function() { return Math.random() - 0.5; }) // sort them randomly (shuffling)
.appendTo(parent); // add them back to parent so that the shuffling takes effect
}
shuffleChildren(parent);
Example:
var parent = $("#node2"); // parent should be the tr element not the tbody which is in fact a grandparent not a parent
function shuffleChildren(parent) {
parent.children() // get the children of the parent element
.sort(function() { return Math.random() - 0.5; }) // sort them randomly (shuffling)
.appendTo(parent); // add them back to parent so that the shuffling takes effect
}
shuffleChildren(parent);
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<table>
<tbody id="parent">
<tr id="node2" class="shufflerow">
<td class="shuffledtd shuffledtd1">AA</td>
<td class="shuffledtd shuffledtd1">BB</td>
<td class="shuffledtd shuffledtd1">CC</td>
<td class="shuffledtd shuffledtd1">DD</td>
</tr>
</tbody>
</table>
Note: If you want to do this to all rows, then just use jQuery#each:
$("#parent tr").each(function() { // get all tr inside #parent
shuffleChildren($(this)); // shuffle their children
});
BTW, what you're shuffling are cells not rows.
ibrahim mahrir's answer is the more elegant way to do what you're trying to do, but in the interest of helping you understand why your solution wasn't working I'm posting this as well.
The Problem:
The problem you were seeing is because when i = 0, when you do (i - 1) you get negative one, which is not a valid index in your table.
rows.eq(i - 1).after(rows[j]);
The way to make your solution work:
Below is how you could have solved that issue with your existing code:
function shuffleRows(parent) {
var rows = parent.children().children(".shuffledtd1");
// Changed to i >= 0.
for (var i = rows.length - 1; i >= 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = rows[i];
// Changed to just i, instead if i-1.
rows.eq(i).after(rows[j]);
rows.eq(j - 1).after(temp);
}
}
$('button').on('click', function() {
shuffleRows($("#parent"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id="parent">
<tr id="node2" class="shufflerow">
<td class="shuffledtd shuffledtd1">AA</td>
<td class="shuffledtd shuffledtd1">BB</td>
<td class="shuffledtd shuffledtd1">CC</td>
</tr>
</tbody>
</table>
<button>Shuffle</button>
This snippet just made two small changes, which I noted in the code, to avoid the negative index problem you had.
Again, there are much more elegant ways to approach this task, but I always get a lot out of understand why something doesn't work, so I wanted you to have an explanation.
Your script can be simplified by great lengths, especially using proper selectors and a random sorter (Covered both cases of sorting td within a tr - or tr within a tbody:
const randomSorter = () => 0.5 - Math.random();
$('.shufflecells tr').each(function() {
$(this).html($('td', this).sort(randomSorter));
});
$('.shufflerows').each(function() {
$(this).html($('tr', this).sort(randomSorter));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table>
<tbody class="shufflecells">
<tr>
<td>AA</td>
<td>BB</td>
<td>CC</td>
<td>DD</td>
</tr>
</tbody>
</table>
<table>
<tbody class="shufflecells">
<tr>
<td>AA</td>
<td>BB</td>
</tr>
</tbody>
</table>
<table>
<tbody class="shufflerows">
<tr>
<td>AA</td>
</tr>
<tr>
<td>BB</td>
</tr>
<tr>
<td>CC</td>
</tr>
<tr>
<td>DD</td>
</tr>
</tbody>
</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().

how to add Class in td If duplicate Data in table

How to add class same record ?
<table>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
<tr>
<td>1</td>
<td>haris</td>
</tr>
<tr>
<td>2</td>
<td>ali</td>
</tr>
<tr>
<td>3</td>
<td>haris</td>
</tr>
</table>
how to add class or how to add style in this duplicate record??
Iterate over all tr and filter out duplicate tr for applying class.
// object for refering text
var obj = {};
// get all tr except the first one which holds header
$('table tr:not(:first-child)').filter(function() {
// get td contents and trim out space
var txt = $('td:last-child', this).text().trim();
// check already defined in object or not
if (txt in obj)
// if defined return true, it's dupe
return true;
// else define the property
obj[txt] = true;
// add class to filtered tr
}).addClass('dup')
// object for refering text
var obj = {};
// get all tr except the first one which holds header
$('table tr:not(:first-child)').filter(function() {
// get td contents and trim out space
var txt = $('td:last-child', this).text().trim();
// check already defined in object or not
if (txt in obj)
// if defined return true, it's dupe
return true;
// else define the property
obj[txt] = true;
// add class to filtered tr
}).addClass('dup')
.dup {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
<tr>
<td>1</td>
<td>haris</td>
</tr>
<tr>
<td>2</td>
<td>ali</td>
</tr>
<tr>
<td>3</td>
<td>haris</td>
</tr>
</table>
</table>

scan table data and replace certain string inside html table

I have following table
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td>
123456789123
</td>
</tr>
</tbody>
</table>
how can I dynamically scan table and replace only values in third table body td values where information like 123456789123 is stored.
This information should be placed with certain character on certain string location so
<td> 123456789123 </td> should be <td> 12345678*12* </td>
Please find below code block for your need, I have added one specific class to TD for which you want to modify value.
$( document ).ready(function() {
$('.value_td').each(function(key, ele){
// Getting Original Value
var original_val = $(ele).text().trim();
// You can change your logic here to modify text
var new_value = original_val.substr(0, 8) + '*' + original_val.substr(9, 2) + '*';
// Replacing new value
$(ele).text(new_value);
});
});
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td class="value_td">
123456789123
</td>
</tr>
</tbody>
</table>
JS Fiddle
To replace the selected texts by indexs, use this:
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
$('td:nth-of-type(3)').each(function(i, item){
$(this).text($(this).text().trim()); // remove extra spaces
$(this).text(replaceAt($(this).text(), 8, '*')); // replace character in position 8
$(this).text(replaceAt($(this).text(), 11, '*')); // replace character in position 11
});
See the working demo: https://jsfiddle.net/lmgonzalves/6ppo0xp3/
Try this:
$('.data td:nth-child(3n)').text('foo');
This will change every 3rd td’s text inside .data to foo. Here’s a demo: http://jsbin.com/katuwumeyu/1/edit?html,js,output
Let me know if that helps, I’ll gladly adapt my answer in case this isn’t what you need.
You can use jquery ":eq(2)" to track 3rd td position like this:
var el = $('table.data tbody tr td:eq(2)');
el.text(el.text().replace('123456789123','12345678*12*'));
https://jsfiddle.net/v25gu3xk/
or maybe you need to replace char positions:
var el = $('table.data tbody tr td:eq(2)');
var vl = el.text().trim();
el.text(vl.substr(0, 8) + '*' + vl.substr(9, 2) + '*');
https://jsfiddle.net/v25gu3xk/1/

How to get html table td cell value by JavaScript?

I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not know how to access the cell value in the Javascript function.
The value of the cell is actually the index of a record and it is hidden in the table. After the record key is located I can retrieve the whole record from db.
How to get the cell value if I do not know the row index and column index of the table that I clicked?
Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:
var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
}
}
var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i = 0, len = cells.length; i < len; i++) {
cells[i].onclick = function() {
console.log(this.innerHTML);
};
}
th,
td {
border: 1px solid #000;
padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
<thead>
<tr>
<th>Column heading 1</th>
<th>Column heading 2</th>
<th>Column heading 3</th>
<th>Column heading 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>43</td>
<td>23</td>
<td>89</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>0</td>
<td>98</td>
</tr>
<tr>
<td>10</td>
<td>32</td>
<td>7</td>
<td>2</td>
</tr>
</tbody>
</table>
JS Fiddle proof-of-concept.
A revised approach, in response to the comment (below):
You're missing a semicolon. Also, don't make functions within a loop.
This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):
function logText() {
// 'this' is automatically passed to the named
// function via the use of addEventListener()
// (later):
console.log(this.textContent);
}
// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');
// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
// the first argument of the anonymous function (here: 'td')
// is the element of the array over which we're iterating.
// adding an event-handler (the function logText) to handle
// the click events on the <td> elements:
td.addEventListener('click', logText);
});
function logText() {
console.log(this.textContent);
}
var cells = document.querySelectorAll('#tableID td');
Array.prototype.forEach.call(cells, function(td) {
td.addEventListener('click', logText);
});
th,
td {
border: 1px solid #000;
padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
<thead>
<tr>
<th>Column heading 1</th>
<th>Column heading 2</th>
<th>Column heading 3</th>
<th>Column heading 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>43</td>
<td>23</td>
<td>89</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>0</td>
<td>98</td>
</tr>
<tr>
<td>10</td>
<td>32</td>
<td>7</td>
<td>2</td>
</tr>
</tbody>
</table>
JS Fiddle proof-of-concept.
References:
Array.prototype.forEach().
document.getElementById().
document.getElementsByTagName().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().
This is my solution
var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
console.log("My contents is \"" + cells[i].innerHTML + "\"");
}
You can use:
<td onclick='javascript:someFunc(this);'></td>
With passing this you can access the DOM object via your function parameters.
I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.
<!DOCTYPE html>
<html>
<head>
<script>
var p = {
onload: function() {
var rows = document.getElementById("mytable").rows;
for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
rows[i].onclick = function() {
alert(this.cells[0].innerHTML);
}
}
}
};
</script>
</head>
<body onload="p.onload()">
<table id="mytable">
<tr>
<td>0</td>
<td>row 1 cell 2</td>
</tr>
<tr>
<td>1</td>
<td>row 2 cell 2</td>
</tr>
</table>
</body>
</html>
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
It works.

Categories