i have a table with number :
<td id="table-number">{{ $loop->index + 1 }}</td>
now i want to get the number of "9" from the table row
Here is what i do :
const number = document.getElementById('table-number');
if(number.textContent.includes('9')) {
console.log('heyhey');
}
but it returns nothing. So, what should i do? I expect to get the table number.
ok guys, i got the answer at this post, sorry i didnt serach thoroughly. Need to upgrade my google skils
Assuming the <td> elements are produced in a loop and you want to know if any of them contain a 9, give the elements a class instead of id...
<td class="table-number">
and try something like this instead
const tableNumbers = Array.from(
document.querySelectorAll(".table-number"),
({ textContent }) => textContent
);
if (tableNumbers.some((content) => content.includes("9"))) {
console.log("heyhey");
}
You probably don't need an id or a class on the cells.
Use querySelectorAll to get a node list of all of the cells, coerce the node list to an array, and then find the cell with the text content that includes your query.
// Cache all the cells
const cells = document.querySelectorAll('td');
// Coerce the node list to an array on which you can
// use the `find` method to find the cell with the matching
// text
const found = [...cells].find(cell => {
return cell.textContent.includes(3);
});
if (found) console.log(found.textContent);
<table>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
Related
I have a table with 3 columns-
<table id="my_list">
<thead>
<tr>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</tr>
</thead>
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
</tr>
</table>
I'm writing a function that searches the table for a given_value and deletes the row that contains it-
function delete_row (given_value) {
var table_row = $("td").filter(function() {
return $('#my_list').text() == given_value;
}).closest("tr");
// Removing the row from `my_list` table
table_row.remove();
}
But this is not deleting the row.
Also, I only want to search the text values in column 2, so if there's a faster way to search the table, that would be great to know too.
I think this is what you are looking for, but you can loop over the td elements and check their text and if you get a match, delete the tr element.
Edit: If you wanted to specify an id, you could add that to the function like such. Then just give the function the id name and what value to look for.
function delete_row(id, given_value) {
var td = $("#" + id + " td");
$.each(td, function(i) {
if ($(td[i]).text() === given_value) {
$(td[i]).parent().remove();
}
});
}
delete_row('my_list', 'value 1');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_list">
<thead>
<tr>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</tr>
</thead>
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
</tr>
</table>
The filter function actually passes a couple things as arguments, including the current element. To check the text of that element, rather than the text of "#my_list", use $(el).text().
After that, 'trim' the value of the text, to remove the whitespace before and after the text. Otherwise its comparing ' value 2 ' with 'value 2', and it will not produce a match.
As a side note, the standard within JavaScript is to use camelCase instead of snake_case.
function deleteRow(givenValue) {
var tableRow = $("td")
.filter(function(index, el) {
return (
$(el) // <-- the <td> element
.text()
.trim() === givenValue
);
})
.closest("tr");
// Removing the row from `my_list` table
tableRow.remove();
}
Are you sure given_value matches the html text? There's spaces before and after text which may be your problem. Also, make sure table_row is not empty after the filter function.
function delete_row(given_value) {
var table_row = $("td").filter(function () {
return $('#my_list').text() == given_value;
});
if (table_row.length > 0) {
// Removing the row from `my_list` table
table_row.closest("tr").remove();
} else {
console.log('nothing matching given_value!')
}
}
Try this simple code:
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}
Call the function as follows:
RemoveFromTable('table ID','value')
You need to match <td> instead of the entire table. Then trim the value to remove any leading/trailing white spaces. Then use the index parameter from the filter function to get the nth <td> element (using eq) and check its value for the desired value, and then remove it.
function delete_row (given_value) {
var table_row = $("td").filter(function(idx) {
return $("td").eq(idx).text().trim() == given_value;
});
// Removing the row from `my_list` table
table_row.remove();
}
I would also suggest to set the value to be an empty string so as to not disrupt the structure of the table.
I am having a table
<table width="100%" border="0" cellpadding="2" cellspacing="0" class="msctrans_navtree">
<tr class="msctrans_navrow" data-subs="603" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents</td>
</tr>
<tr class="msctrans_navrow" data-subs="" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test 1</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents 1</td>
</tr>
<tr class="msctrans_navrow" data-subs="334,23,5,21" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test 2</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents 2</td>
</tr>
Clicking on the TR with class "msctrans_navrow" should do something regarding the data parameters of the clicked element:
$(".msctrans_navrow").click(function() {
var clicked = $(this);
var subs = clicked.data("subs");
var navlevel = clicked.data("navlevel");
var sp_id = clicked.data("sp_id");
var spstandard = clicked.data("standardsprache");
alert(subs + " = " + subs.length);
// Action only if there are subs
if (subs.length) {
clicked.toggleClass("mscajaxloaderdivabsolut");
var insertAfter = clicked.next();
alert("Now I am doing some Ajax and inert it after the inserAfter element.");
}
});
Unfortunately when clicking the first TR where the data-subs parameters value is 603 subs.length in the script delivers an "undefined". I can't figure why that is.
Here is a fiddle to play around with it: http://jsfiddle.net/9B9AW/9/
It's because it's stored as a number, not a string, inside jQuery's data cache for that element. Numbers don't have a length property. You could force a conversion to string by calling .toString():
if(subs.toString().length) {
// code if the string representation of `subs` has a length > 0
}
Alternatively you could use the .attr() method instead, which won't convert (always retrieves the value as a string):
var subs = clicked.attr("data-subs");
Change var subs = clicked.data("subs");
to var subs = ""+clicked.data("subs"); // make it a String
Demo ---> http://jsfiddle.net/9B9AW/10/
I'm trying to create a show/hide function for data within a table populated with data from a mssql database. The function should look for rows with the same value in the "capability" column and onclick, hide all rows with the same value. After this, a row is inserted into the table with the same capability value, but summarizes the data in the hidden rows. This should work in the way that grouping cells together works in excel.
I've managed to get this to work, but it only works for the first click and I receive a "cannot read innerHTML property of NULL" for any of the function's calls after that.
function compactRows(thisrow) {
var totalRows = document.getElementById("DataTable").getElementsByTagName("tr").length;
var summaryVal1= [];
var summaryVal2= [];
for(var i = 1; i < totalRows;i++) {
var trID = "capability" + i;
if(thisrow.innerHTML == document.getElementById(trID).innerHTML) { //The error gets returned on this line
summaryVal1.push(document.getElementById(trID).parentNode.children[5].innerHTML);
summaryVal2.push(document.getElementById(trID).parentNode.children[14].innerHTML);
document.getElementById(trID).parentNode.style.display = 'none';
}
}
createNewRow(thisrow, summaryVal1, summaryVal2);
}
//I took out the logic for the data summarizing in the createNewRow function because I don't think its relevant to the issue I'm having. Also, I didn't want to crowd the area with unrelated code
function createNewRow(row, ibxMobile, overallStatus) {
var table = document.getElementById("DataTable");
var localRow = table.insertRow(row.parentNode.rowIndex);
var cell1 = localRow.insertCell(0);
cell1.setAttribute("id", "entry1");
var cell2 = localRow.insertCell(0);
cell2.setAttribute("id", "Capability");
cell2.innerHTML = row.innerHTML;
var cell3 = localRow.insertCell(0);
cell3.setAttribute("id", "entry3");
}
The function called at the bottom, createNewRow, handles making the row to be entered after all the rows are hidden. It also, handles the logic for summarizing the hidden rows.
All help is greatly appreciated! Thank you
Edit 1: example table set up
<table>
<tr>
<th>Entry1 </th>
<th>Capability</th>
<th>Entry3 </th>
</tr>
<tr>
<td>1.1</td>
<td id="Capability1" onclick="compactRows(this)">Lasers</td>
<td>stuff</td>
</tr>
<tr>
<td>1.2</td>
<td id="Capability2" onclick="compactRows(this)">Lasers</td>
<td>things</td>
</tr>
<tr>
<td>2.1</td>
<td id="Capability3" onclick="compactRows(this)">Beams</td>
<td>more things</td>
</tr>
</table>
//The Below table is what it looks like after clicking either of the first two entries
<table>
<tr>
<th>Entry1 </th>
<th>Capability</th>
<th>Entry3 </th>
</tr>
<tr>
<td>1</td>
<td id="Capability">Lasers</td>
<td></td>
</tr>
<tr>
<td>2.1</td>
<td id="Capability3" onclick="compactRows(this)">Beams</td>
<td>more things</td>
</tr>
</table>
There is no "Capability1" id for any rows after the "CreateNewRow" is called. Therefore, the second time "CompactRows()" is called a null reference is thrown when accessing "document.getElementById("Capability1").innerHTML". Rework the CreateNewRow to inlcude the increment for the Capability id value or test that "getElementById" actually returns an object before attempting to access the innerHTML method.
I have an HTML table with combined row td's, or how to say, I don't know how to express myself (I am not so good at English), so I show it! This is my table:
<table border="1">
<thead>
<tr>
<th>line</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>1.3</td>
<td>1.4</td>
</tr>
<tr>
<td rowspan="2">2</td>
<td>2.1</td>
<td>2.2</td>
</tr>
<tr>
<td>2.3</td>
<td>2.4</td>
</tr>
</tbody>
</table>
(you can check it here)
I want to convert this table to a JSON variable by jquery or javascript.
How should it look like, and how should I do it? Thank you, if you can help me!
if you want to convert only text use this one :
var array = [];
$('table').find('thead tr').each(function(){
$(this).children('th').each(function(){
array.push($(this).text());
})
}).end().find('tbody tr').each(function(){
$(this).children('td').each(function(){
array.push($(this).text());
})
})
var json = JSON.stringify(array);
To make a somehow representation of your table made no problem to me, but the problem is how to parse it back to HTML! Here a JSON with the first 6 tags:
{"table":{"border":1,"thead":{"th":{"textContent":"line","tr":"textContent":"value1",...}}}}}...
OR for better understanding:
{"tag":"table","border":1,"child":{"tag":"thead","child":{"tag":"th","textContent":"line",
"child":{"tag":"tr","textContent":"value1","child":...}}}}...
Closing tags are included.
For further explanations I need to know whether your table is a string or part of the DOM.
I belive this is what you want:
var jsonTable = {};
// add a new array property named: "columns"
$('table').find('thead tr').each(function() {
jsonTable.columns = $(this).find('th').text();
};
// now add a new array property which contains your rows: "rows"
$('table').find('tbody tr').each(function() {
var row = {};
// add data by colum names derived from "tbody"
for(var i = 0; i < jsonTable.columnsl.length; i++) {
row[ col ] = $(this).find('td').eq( i ).text();
}
// push it all to the results..
jsonTable.rows.push( row );
};
alert(JSON.stringify(jsonTable));
I think there should be some corrections, but this is it I think.
I'm trying to filter table rows in an intelligent way (as opposed to just tons of code that get the job done eventually) but a rather dry of inspiration.
I have 5 columns in my table. At the top of each there is either a dropdown or a textbox with which the user may filter the table data (basically hide the rows that don't apply)
There are plenty of table filtering plugins for jQuery but none that work quite like this, and thats the complicated part :|
Here is a basic filter example http://jsfiddle.net/urf6P/3/
It uses the jquery selector :contains('some text') and :not(:contains('some text')) to decide if each row should be shown or hidden. This might get you going in a direction.
EDITED to include the HTML and javascript from the jsfiddle:
$(function() {
$('#filter1').change(function() {
$("#table td.col1:contains('" + $(this).val() + "')").parent().show();
$("#table td.col1:not(:contains('" + $(this).val() + "'))").parent().hide();
});
});
Slightly enhancing the accepted solution posted by Jeff Treuting, filtering capability can be extended to make it case insensitive. I take no credit for the original solution or even the enhancement. The idea of enhancement was lifted from a solution posted on a different SO post offered by Highway of Life.
Here it goes:
// Define a custom selector icontains instead of overriding the existing expression contains
// A global js asset file will be a good place to put this code
$.expr[':'].icontains = function(a, i, m) {
return $(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// Now perform the filtering as suggested by #jeff
$(function() {
$('#filter1').on('keyup', function() { // changed 'change' event to 'keyup'. Add a delay if you prefer
$("#table td.col1:icontains('" + $(this).val() + "')").parent().show(); // Use our new selector icontains
$("#table td.col1:not(:icontains('" + $(this).val() + "'))").parent().hide(); // Use our new selector icontains
});
});
This may not be the best way to do it, and I'm not sure about the performance, but an option would be to tag each column (in each row) with an id starting with a column identifier and then a unique number like a record identifier.
For example, if you had a column Produce Name, and the record ID was 763, I would do something like the following:
<table id="table1">
<thead>
<tr>
<th>Artist</th>
<th>Album</th>
<th>Genre</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td id="artist-127">Red Hot Chili Peppers</td>
<td id="album-195">Californication</td>
<td id="genre-1">Rock</td>
<td id="price-195">$8.99</td>
</tr>
<tr>
<td id="artist-59">Santana</td>
<td id="album-198">Santana Live</td>
<td id="genre-1">Rock</td>
<td id="price-198">$8.99</td>
</tr>
<tr>
<td id="artist-120">Pink Floyd</td>
<td id="album-183">Dark Side Of The Moon</td>
<td id="genre-1">Rock</td>
<td id="price-183">$8.99</td>
</tr>
</tbody>
</table>
You could then use jQuery to filter based on the start of the id.
For example, if you wanted to filter by the Artist column:
var regex = /Hot/;
$('#table1').find('tbody').find('[id^=artist]').each(function() {
if (!regex.test(this.innerHTML)) {
this.parentNode.style.backgroundColor = '#ff0000';
}
});
You can filter specific column by just adding children[column number] to JQuery filter. Normally, JQuery looks for the keyword from all the columns in every row. If we wanted to filter only ColumnB on below table, we need to add childern[1] to filter as in the script below. IndexOf value -1 means search couldn't match. Anything above -1 will make the whole row visible.
ColumnA | ColumnB | ColumnC
John Doe 1968
Jane Doe 1975
Mike Nike 1990
$("#myInput").on("change", function () {
var value = $(this).val().toLowerCase();
$("#myTable tbody tr").filter(function () {
$(this).toggle($(this.children[1]).text().toLowerCase().indexOf(value) > -1)
});
});
step:1 write the following in .html file
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
</table>
step:2 write the following in .js file
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}