Remove table row by finding content with clause - javascript

I have this code:
<table>
<tbody>
<tr><td>Table 1</td></tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td align="left">Number</td>
<td><b>33</b></td>
</tr>
<tr>
<td width="150" align="left">Field</td>
<td>XXXX</td>
</tr>
<tr>
<td align="left">Select: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
</tbody>
</table>
and i want to remove this line by searching "Field" with pure Javascript:
<tr>
<td width="150" align="left">Field</td>
<td>XXXX</td>
</tr>
when there is a 33, 66 or 99 in this line from my 2nd table:
<tr>
<td align="left">Number</td>
<td>33</td>
</tr>
The problem is that i don't have any id's or classes for identification! i want to use the code with Greasemonkey.
Here you can see a JSFIDDLE of my table.
And here you can see on JSFIDDLE how it should look.
Best regards bernte

Here you go:
var disallowedValues = ['33', '66', '99'];
var cols = document.getElementsByTagName('td');
var colslen = cols.length;
var i = -1;
var disallowedTable;
while(++i < colslen){
// look for the td where the disallowed values are
if(disallowedValues.indexOf(cols[i].innerHTML) >= 0)
{
// get the table where the disallowed values is
disallowedTable = cols[i].parentNode.parentNode.parentNode;
// break the cicle to stop looking for other rows
//break;
}
}
// look for the 'Field' value only on the table that has the disallowed value
var cols = disallowedTable.getElementsByTagName('td');
cols = disallowedTable.getElementsByTagName('td');
colslen = cols.length;
i = -1;
while(++i < colslen){
// look for the td where the 'Field' value is
if(cols[i].innerHTML == 'Field')
{
// get the tr for such td
var deletionTR = cols[i].parentNode;
//delete that tr
deletionTR.parentNode.removeChild(deletionTR);
// break the cicle to stop looking for other rows
break;
}
}
You can always do a simpler version if jquery is an option.

Related

how to select a range of html table cell value in javascript?

Please help!
I have a html table and for example I want to select the first 4 cell value of the table but I don't know how.
I tried:
var table = document.getElementById("td")
selectedCell = table.cells[0:4]
javascript does not understand this way.
You can access a cell by its row index and cell index like this:
var table = document.getElementById('table1')
for(let rowIndex = 0; rowIndex < 2; rowIndex++){
for(let cellIndex = 0; cellIndex < 2; cellIndex++){
console.log(table.rows[rowIndex].cells[cellIndex]);
}
}
<table id="table1" style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
<tr>
<td>March</td>
<td>$70</td>
</tr>
<tr>
<td>April</td>
<td>$160</td>
</tr>
</table>
if you give some sample data and an expected output I can use it to help you to make adjustment to this.

Print array in the table td

I am new in Javascript, I have an array, and want to print it in the table td.
This is my array:
array = [100, 200, 300];
This is my table:
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
I want to print my array in the td with class name 'result'
You can use querySelectorAll() and Node.textContent:
const array = [100, 200, 300];
const elements = [...document.querySelectorAll('.result')];
for(let i = 0; i < array.length; i++) {
elements[i].textContent = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Just iterate over the array and use the current index for the HTML element as well.
Possible ES5-only solution:
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
document.getElementsByClassName("result")[i].innerHTML = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Note: You need an equal amount of array elements and elements with the .result class.
Assign an id attribute to the table tag, id = "tab". Then add the below javascript code
pointer=0
arr=[100,200,300];
// selecting all the tags having result as class name
var nodes=document.getElementById("tab").getElementsByClassName("result");
arr.forEach((ele)=>{nodes[pointer].innerHTML=ele;pointer+=1});
Look at this example:
I use querySelectorAll
It considers the case if the array elements and the quantity of rows are diffrerent.
Also added '.myTable' to prevent target other '.result' nodes out of the selected table.
Hope it helps.
<table class="myTable">
<th> Result</th>
<tbody>
<tr><td> My result 1</td><td class='result'></td></tr>
<tr><td> My result 2</td><td class='result'></td></tr>
<tr><td> My result 3</td><td class='result'></td></tr>
<tr><td> My result 4</td><td class='result'></td></tr>
</tbody>
</table>
<script>
const array = [100, 200, 300];
const rows = document.querySelectorAll('.myTable .result') // <-- I added '.myTable' to prevent target other '.result' nodes out of the selected table
rows.forEach((row, i) => {
if (array[i]) row.innerHTML = array[i] // <-- I replace the innerHTML if the array has content at that index
});
</script>
You can do this,
var result = document.getElementsByClassName("result")
var array = [100,200,300]
for (var i=0;i<result.length;i++){
result[i].innerHTML = array[i];
}
Demo
Hope this helps you... No need to update table according to array data....
Table code:
<table>
<th colspan="2" >Result</th>
<tbody id="myTableBody"></tbody>
</table>
JavaScript code:
<script>
var tableRef = document.getElementById('myTableBody');
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
tableChild = document.createElement('tr');
tableChild.innerHTML = "<td> My result "+(i+1)+"</td><td class='result'>"+array[i]+"</td>";
tableRef.appendChild(tableChild);
}
</script>
Example: https://codepen.io/Nishanth_V/pen/rEZmxN
var el = document.getElementsByClassName('result');
var array = [100, 200, 300];
for(var i =0 ; i < el.length && i < array.length; ++i) {
el[i].innerHTML = array[i];
}
You have to replace ' by " and add numbers to your class , after that your code with look like this:-
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class="result1"></td>
</tr>
<tr>
<td> My result 2</td>
<td class="result2"></td>
</tr>
<tr>
<td> My result 3</td>
<td class="result3"></td>
</tr>
</tbody>
</table>
Your JavaScript code will look like this:-
<script>
var array = [100, 200, 300];
array.foreach(function (item, index){
var resultNum = index + 1;
document.getElementByClassName("result" + resultNum).innerHTML = item;
});
</script>

Read all td values with Javascript

I am trying to get all td and compare each td value to a string .
but my code only reads the first td of each tr.
Here is my HTML :
<table border="2px" id="tab">
<tr>
<td>color</td>
<td> a </td>
<td> font</td>
<td>123</td>
</tr>
<tr>
<td>font</td>
<td> color </td>
</tr>
<tr>
<td>a</td>
<td> color</td>
<td> font</td>
</tr>
<tr>
<td>font</td>
</tr>
</table>
My js code:
var t=["color","font","a"];
function color()
{
var colr=0;
var tab=[];
var table = document.getElementById("tab");
var len=table.rows.length;
for (var i = 0; i< len; i++)
{
for (var j=0; j<table.rows[i].cells.length; j++)
{
tab[j]= table.rows[i].cells[j].innerHTML;
// alert(tab[j]);
if(tab[j]== t[0])
{ colr++;}
}
}
alert(colr);
}
What am I missing?
The spacing in the <td> is messing with the comparisons. As your code lies, you're comparing " color" to "color" and that's returning false, thus seeing as you're only getting that colr index going up to 1.
You'll need to strip out the spaces in order to compare properly, example JSFiddle here: https://jsfiddle.net/76q3aro3/

Highlight table cell based on vertical and horizontal headers

I have a "football squares" game going, and I would like to highlight cells of the winners based on the top and side headers.
Now, I know they're not really headers but they serve the same purpose.
My table is located at this jfiddle: https://jsfiddle.net/8ybtntqg/
What I want to do is this:
Let's say the winner would be whoever is in the cell that lines up with TeamA - 2 and TeamZ - 9. That would be Mitch. I want to highlight Mitch's cell. How would I do this with Javascript or Jquery? I know how to do it if I was just looking for the word "Mitch", but I want to automatically do it, based on the numbers of TeamA and TeamZ.
I have this so far, but of course that only highlights the name but it's the only place I knew to start:
$('#table_id td').each(function() {
if ($(this).text() == 'Mitch') {
$(this).closest('td').css('background-color', '#f00');
}
});
You can get the index of the column and row using jQuery's filter() method.
That will give you direct access to the cell like so:
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
Snippet:
function highlight(teamA, teamZ) {
var col, row;
col = $('#table_id td').filter(function() { //return column of teamA
return $(this).html() === teamA.replace(' - ', '<br>');
}).index();
row = $('#table_id tr').filter(function() { ////return row of teamZ
return $(this).html().indexOf(teamZ.replace(' - ', '<br>')) > -1;
}).index();
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
}
highlight('TeamA - 2', 'TeamZ - 9');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="table_id">
<tr>
<td>Squares</td>
<td>TeamA<br>1</td>
<td>TeamA<br>2</td>
<td>TeamA<br>3</td>
<td>TeamA<br>4</td>
<td>TeamA<br>5</td>
<td>TeamA<br>6</td>
<td>TeamA<br>7</td>
<td>TeamA<br>8</td>
<td>TeamA<br>9</td>
<td>TeamA<br>0</td>
</tr>
<tr>
<td>TeamZ<br>3</td>
<td bgcolor="#89ff89">Mark</td>
<td bgcolor="#89ff89">John</td>
</tr>
<tr>
<td>TeamZ<br>5</td>
<td bgcolor="#89ff89">Mike</td>
<td bgcolor="#89ff89">Earl</td>
</tr>
<tr>
<td>TeamZ<br>8</td>
<td bgcolor="#89ff89">Morris</td>
<td bgcolor="#89ff89">Brice</td>
</tr>
<tr>
<td>TeamZ<br>7</td>
<td bgcolor="#89ff89">Taylor</td>
<td bgcolor="#89ff89">Evan</td>
</tr>
<tr>
<td>TeamZ<br>9</td>
<td bgcolor="#89ff89">Mandy</td>
<td bgcolor="#89ff89">Mitch</td>
</tr>
<tr>
<td>TeamZ<br>2</td>
<td bgcolor="#89ff89">Tony</td>
<td bgcolor="#89ff89">Jennifer</td>
</tr>
<tr>
<td>TeamZ<br>1</td>
<td bgcolor="#89ff89">Kristen</td>
<td bgcolor="#89ff89">Hector</td>
</tr>
<tr>
<td>TeamZ<br>4</td>
<td bgcolor="#89ff89">Gabby</td>
<td bgcolor="#89ff89">David</td>
</tr>
<tr>
<td>TeamZ<br>6</td>
<td bgcolor="#89ff89">George</td>
<td bgcolor="#89ff89">Steffanie</td>
</tr>
<tr>
<td>TeamZ<br>0</td>
<td bgcolor="#89ff89">Breck</td>
<td bgcolor="#89ff89">Terry</td>
</tr>
</table>
You can iterate over all the table elements to find the matching values, then use CSS selectors to highlight the matched field. Something like this will work:
winningAScore = 2;
winningZScore = 9;
//get top row
counter = 0;
$('#table_id tr:first-child td').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningAScore) {
posnX = counter;
}
counter++;
})
//get first column row
counter = 0;
$('#table_id tr td:first-child').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningZScore) {
posnY = counter;
}
counter++;
})
$('tr:eq('+posnY+') td:eq('+posnX+')').css('background-color', 'red');
You can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/8ybtntqg/1/
You can do index based detect and selection in jQuery like so: $('tr:eq(2) td:eq(1)').css('background-color', 'red');
Example: http://codepen.io/anon/pen/EPLNvB

Search the table by cell content with jquery and relative referencing

Having such table
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> 1 </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> x </td>
<td class="TableCol3"> # </td>
</tr>
<tr class="TableEven">
<td>....</td>
</tr>
</tbody>
E.g. each cell has own class indicating it's column number TableCol0,1,2..N
In each row, needed compare the content of the cells in column 1 and 2 and write the result into colum3.
Managed the following script,
$(document).ready(function() {
var toterr = 0;
$('tbody tr.TableEven,tbody tr.TableOdd').each(function() {
var wanted = $(this).find('.TableCol1' ).html();
var actual = $(this).find('.TableCol2' ).html();
//console.log('wanted='+wanted+'=actual='+actual+'=');
if ( wanted == actual ) {
$(this).find('.TableCol3').text('ok');
} else {
$(this).find('.TableCol3').text('ERROR');
toterr++;
}
});
$('#totalerror').text(toterr);
});
It is probably not optimal, but works.
Now have a bit different scenario: Need compare two cells what are before a cell with a specified content (:CMP:), e.g:
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> x </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> :CMP: </td>
<td class="TableCol3"> etc </td>
</tr>
<tr class="TableEven">
<td class="TableCol0"> N </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> y </td>
<td class="TableCol3"> :CMP: </td>
</tr>
</tbody>
For each row, need compare cells what are before :CMP:, and replace the :CMP: with the result. e.g.
in the 1st row need compare the x and x and write ok in the cell .TableCol2
in the 2nd row need compare the x and y and write ERROR in the cell .TableCol3
I haven't idea how to modify the above script.
Can easily get the index of the cell that contains ':CMP:' and use the index to reference the previous cells. Or use traverses like prev() or use eq() once index is found.
$('tbody tr').each(function () {
var $cells = $(this).children(),
$cmp = $cells.filter(':contains(":CMP:")'),
cmpIndex = $cells.index($cmp);
// array of values of previous cells
var values = $.map($cells.slice(cmpIndex - 2, cmpIndex), function (el) {
return $.trim($(el).text());
});
// make sure we have 2 cells with values and compare
var cmpText = values.length === 2 && values[0] === values[1] ? 'OK' : 'ERROR';
$cmp.text(cmpText);
});
DEMO

Categories