Changing <td> <i> CSS based on the value - javascript

I have been asked to implement a small validation on values and if the values are greater or less than 0 i need to change or add/remove the css for the td and i tag
My table looks something like this
<table class="table table-hover" id="studentweek">
<thead>
<tr>
<th>Year</th>
<th">Weeks</th>
</tr>
</thead>
<tbody>
<tr>
<td>VAR (%)</td>
<td class="text-warning"> <i class="classname">-10.65%</i></td>
</tr>
<tr>
<td>VAR (diff)</td>
<td class="text-warning"> <i class="classname">-13,953</i></td>
</tr>
<tr>
<td>VAR (%)</td>
<td class="text-navy"> <i class="classname">8.81%</i></td>
</tr>
<tr>
<td>VAR (diff)</td>
<td class="text-navy"> <i class="classname">11,320</i></td>
</tr>
</tbody>
</table>
currently i am hard coding the css but i would like to be able to dynamicly change these as the values change automatically, can someone suggest the best way to archive this?
i was thinking in my Ajax request to do something like this:
var sdlyvar = $(parseFloat(".classname").text());
if (sdlyvar < 0){
$('.classname').removeClass(".classname").addClass("fa-level-down");
} else {
$('.classname').removeClass(".classname").addClass("fa-level-up");
}

Use JavaScript parseFloat for parsing percentage (http://www.w3schools.com/jsref/jsref_parsefloat.asp).
var percent = $('#sdlyvar').text();
var result = parseFloat(percent) / 100.0;
if (result < 0){
$('#sdlyvar').removeClass("fa-level-up");
$('#sdlyvar').addClass("fa-level-down")
} else {
$('#sdlyvar').removeClass("fa-level-down");
$('#sdlyvar').addClass("fa-level-up")
}

Your first problem is that you can't compare a string like "-10.95%" with an integer, because of the final % symbol. You have to use parseFloat on tha value:
var sdlyvar = parseFloat($('#sdlyvar').text());
It will take care of all the non-numeric stuff after the number.
Then, you'd probably want to remove the opposite class when updating:
if (sdlyvar < 0){
$('#sdlyvar').removeClass("fa-level-up").addClass("fa-level-down");
} else {
$('#sdlyvar').removeClass("fa-level-down").addClass("fa-level-up");
}
A few random suggestions:
Make clear what's wrong in your code when posting on StackOverflow
When referring an element more than once with jQuery, consider putting the selection in a variable, like var $sdlyvar = $("sdlyvar");: faster to type and execute.
Save us some whitespaces when posting code :/

Here .slice will remove the % sign in this code and the rest of the code will compare the value and assign or remove class
var sdlyvar = $('#sdlyvar').text();
if (sdlyvar.slice(0,-1) < 0){
$('#sdlyvar').removeClass("fa-level-up");
$('#sdlyvar').addClass("fa-level-down");
} else {
$('#sdlyvar').removeClass("fa-level-down");
$('#sdlyvar').addClass("fa-level-up");
}

var lis=document.querySelectorAll("tr td i");
for(var i in lis){
if(parseInt(lis[i].innerHTML)<0){
lis[i].className+=" fa-level-down";
}
else{
lis[i].className+=" fa-level-up";
}
}

Related

How to use Javascript to determine what was the last class in a table?

I'm trying to create an if function that'd check if the second tr's class is success or danger. Let's say that it'd set the value of x to 0 if it's success and it'd set the value of z to 0 if it's danger. I'm not qute sure if it's even possible to do with Javascript but any help is appreciated. Here's some code that I thought can be useful to answering this question, but I can't get my head around it.
function hasClass(element, className) {
return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
}
var myDiv = document.getElementById('myBetsTable');
hasClass(myDiv, 'success');
P.S. These classes are constantly changing.
P.S.2 It must be coded in plain Javascript
The bootstrap success and danger classes are used as a method of color coding. This leads me to believe this is some sort of sports betting website.
Because of the sensitivity of this information, it would be much better to enclose this on the server side. This code should definitely not be used in production by itself, but is mainly used to provide a minimal example.
JavaScript Solution
You'll want to create a collection of tr elements by calling getElementsByTagName
In this example, I will be using the onclick event attribute to listen for a mouse click. In a production application, this would be used some other way. Once the event has been recorded, the function to check the last bet (win or loss) will be recorded.
To get the last table row, we can use rows[rows.length-1]. We need to use this, because JS arrays are zero indexed.
I've provided a new function for adding new rows to the table. In sports betting, the tables are not fixed, but can change dynamically. Once again, in production this would look much differently.
Upon clicking Grade Ticket, a new row will appear. As sports is random and betting is discouraged, you are not guaranteed to win. So, you will either randomly win or randomly lose an event. You can then click Set Variables again to see the new result. It will change.
var rows = document.getElementsByTagName("tr");
var betsTable = document.getElementById("bets-table");
function setVariables() {
var lastBet = rows[rows.length - 1];
alert(lastBet.classList.contains("success") ? "x = 0" : "z = 0");
}
function gradeTicket() {
var gradedWager = document.createElement("tr");
var matchup = document.createElement("td");
var result = document.createElement("td");
if (Math.random() > 0.5) {
gradedWager.classList.add("success");
result.innerHTML = "WIN";
}
else {
gradedWager.classList.add("danger");
result.innerHTML = "LOSS";
}
var teams = document.createTextNode("Team A versus Team B");
matchup.appendChild(teams);
gradedWager.appendChild(matchup);
gradedWager.appendChild(result);
betsTable.appendChild(gradedWager);
}
.success { background: #5cb85c; }
.danger { background: #d9534f; }
#bets-table td {
padding: 10px;
}
#check-last-bet {
margin-top: 5%;
}
<table id="bets-table">
<tbody>
<tr class="success">
<td>Pacers versus Lakers</td>
<td>WIN $1400</td>
</tr>
<tr class="danger">
<td>Celtics versus Clippers</td>
<td>LOSS $1250</td>
</tr>
<tr class="success">
<td>Bulls versus Warriors</td>
<td>WIN $300</td>
</tr>
<tr class="danger">
<td>Oregon versus Ohio State</td>
<td>LOSS $450</td>
</tr>
<tr class="success">
<td>Manchester United versus Chelsea</td>
<td>WIN $500</td>
</tr>
</tbody>
</table>
<button id="check-last-bet" onclick="setVariables()">Check Last Bet</button>
</br></br>
<button id="grade-ticket" onclick="gradeTicket()">Grade Ticket</button>
In modern browsers faster and easier way to do this would be use the native document.querySelector method along with the nth-child CSS selector.
This avoids scraping through all the TR elements on the page.
var tr = document.querySelector("#myBetsTable tr:nth-child(2)");
var cls = tr.getAttribute('class');
if( cls === 'danger' ) {
console.log(cls);
} else {
console.log('not danger')
}
See jsfiddle example
You can create a function that checks the class using the classList property on DOM objects.
function checkClass() {
var td = document.querySelectorAll('tr')[1];
if (td.classList.contains('success')) {
x = 0;
}
else if (td.classList.contains('danger')) {
z = 0;
}
If the classes are dynamically changing you can tie the function to an event listener or AJAX call or however the classes change.
You can get the class by counting the rows and get the classname of last row
var x = document.getElementById("myTable").rows.length;
alert(document.getElementById("myTable").rows[x-1].className);
function myFunction() {
var x = document.getElementById("myTable").rows.length;
alert(document.getElementById("myTable").rows[x-1].className);
}
<table id="myTable">
<tr class="0">
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr class="1">
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr class="2">
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<button onclick="myFunction()">Get Class</button>

Multiply td values

I have a html table that looks like this...
<table>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</table>
<p>Total number is:MULTIPLICATION OF ALL CHANCE COLUMN TD</p>
all my rows are added dynamically,how do i multiply all chance column td values(numbers)?Do i have to put certain class on chance tds and then get all tds with that class,and loop through and multiply every value then?I'm kinda a newbie so any help would be appreciated.
You can either do something like this:
var tots = 1;
$('tr td:nth-child(4)').each(function(){
tots *= $(this).text();
});
the nth-child(4) is selecting the fourth td in each row, if you want another, just change that number.
or you can give the cells you want to multiple classes, like you said.
example here
If you're using jQuery, the :last-child selector could be helpful.
<p>Total number is: <span id="result"></span></p>
Javascript:
res = 1;
$("tr td:last-child").each(function() {
res *= parseFloat($(this).html());
});
$("#result").html(res);
Have a look to this JSFiddle.
You don't need jQuery to do this. querySelectorAll supports nth-child selector as well.
var derp = document.querySelectorAll("tr td:nth-child(4)");
var total = 1;
var results = [].reduce.call(derp, function (prev, next) {
return prev * ( + next.textContent );
});
Grab the element, and use native Array prototype methods ([]) to iterate the NodeList and return the parsed value of the element, then return the multiplied total.
Here is a fiddle for you.
$(function () {
var chanceTotals = 1;
$("tr td:nth-child(4)").each(function () {
chanceTotals *= parseFloat($(this).html());
});
$("#totals").html("Total number is: " + chanceTotals);
});
Using jQuery, this executes an anonymous function when the document is ready that will do the calculation for you.
You will need to add the id totals to your p element in order for this to work.
Look at this JSFiddle
You really do not need jquery at all to do this. Interacting with the DOM directly may make you write more (browser support), but it can be more efficient than using jQuery (Unnecessary overhead).
As you can see, I restructured your <table>. I could have just grabbed the <tbody> and looped over its children and skipped the whole if <TD> ? check.
DEMO
$(document).ready(function () {
var table = $('#myTable').get(0);
var multiplier = 1;
var col = 3;
for (var row = 0; row < 4; row++) {
var cell = table.rows[row].cells[col];
if (cell.nodeName == 'TD') {
var text = cell.innerText || cell.textContent;
multiplier *= parseFloat(text);
}
}
$('#multiplier').text(multiplier);
});
<table id="myTable">
<thead>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
</thead>
<tbody>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</tbody>
</table>
<p>Total number is:
<span id="multiplier">MULTIPLICATION OF ALL CHANCE COLUMN TD</span>
</p>

how to convert/transform an HTML table tbody (with rowspans) TO json?

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.

how to sum columns of html table generated from database in jsp using javascript?

I am working on my site and i want to sum the values in one column of html table using javascript over a jsp. I have found various codes which can add static data which has been put in already but when i use same thing in my code it doesnt work.
The javascript is as follows:-
<script type="text/javascript">
var debugScript = true;
function computeTableColumnTotal(tableId, colNumber)
{
var result = 0;
try
{
var tableElem = window.document.getElementById(tableId);
var tableBody = tableElem.getElementsByTagName("tbody").item(0);
var i;
var howManyRows = tableBody.rows.length;
for (i=1; i<(howManyRows-1); i++) // skip first and last row (hence i=1, and howManyRows-1)
{
var thisTrElem = tableBody.rows[i];
var thisTdElem = thisTrElem.cells[colNumber];
var thisTextNode = thisTdElem.childNodes.item(0);
if (debugScript)
{
window.alert("text is " + thisTextNode.data);
} // end if
// try to convert text to numeric
var thisNumber = parseFloat(thisTextNode.data);
// if you didn't get back the value NaN (i.e. not a number), add into result
if (!isNaN(thisNumber))
result += thisNumber;
} // end for
} // end try
catch (ex)
{
window.alert("Exception in function computeTableColumnTotal()\n" + ex);
result = 0;
}
finally
{
return result;
}
}
function finishTable()
{
if (debugScript)
window.alert("Beginning of function finishTable");
var tableElemName = "hikeTable";
//idhar column define kar raha hai wo
var totalMilesPlanned = computeTableColumnTotal("hikeTable",2);
var totalMilesHiked = computeTableColumnTotal("hikeTable",3);
try
{
var totalMilesPlannedElem = window.document.getElementById("totalMilesPlanned");
document.getElementById("total_1").innerHTML = totalMilesPlanned;
var totalMilesHikedElem = window.document.getElementById("totalMilesHiked");
document.getElementById("total_2").innerHTML = totalMilesHiked ;
}
catch (ex)
{
window.alert("Exception in function finishTable()\n" + ex);
}
return;
}
</script>
This works when html table is like
<html>
<body onload="finishTable();">
<tbody>
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td>1324</td>
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>1176576523</td>
<td>23</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>67</td>
<td>98</td>
</tr>
<tr>
<td colspan="2">Total </td>
<td id="total_1"></td>
<td id="total_2"></td>
</tr>
</tbody>
<table>
</html>
But my table is something like this :-
<html>
<body onload="finishTable();">
<tbody>
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);
while(rs.next()){
int buildarea = rs.getInt("build_area");
int numberoflevels = rs.getInt("no_of_levels");
%>
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td><%=buildarea%></td> //here a value comes from database
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>bumberoflevels</td>
<td>23</td>
</tr>
<td colspan="2">Total </td>
<td id="total_1"></td>
<td id="total_2"></td>
</tr>
</tbody>
<%}%>
<table>
</html>
Please help!!
Just some them over:
int totalBuildArea = 0;
int totalNoOfLevels = 0;
while(rs.next()){
int buildarea = rs.getInt("build_area");
int numberoflevels = rs.getInt("no_of_levels");
%>
...
...
The total row should be out of the loop.
...
...
totalBuildArea += buildarea ;
totalnumberOfLevels += numberoflevels ;
<%}%>
<td colspan="2">Total </td>
<td id="total_1"><%=totalBuildArea %></td>
<td id="total_2"><%=totalnumberOfLevels %></td>
That said,
What you are doing does not sound right at all.
For one, accessing the database from JSP is not a good idea. What you need is a good three tire architecture. You can use frameworks like struts. Or at least have your own Business Logic classes, and call them from your servlet.
Even if this is the only way for whatever reason, your JSP itself does not look correct.
Consider this:
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td><%=buildarea%></td> //here a value comes from database
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>bumberoflevels</td>
<td>23</td>
Part of the data is hardcoded. Part of the data is from the database. The columns are not right. <tr>s don't end. For me this does not look like the actual code. Or it is and you have not put complete effort in giving all the details.
Try working on the JSP. Come up with a structure you want. There can be pieces that you don't know how to do. That is fine. Ask them as questions. We are here to help.
But we can help only when you ask a proper question. One simple rule: Imagine You're Trying To Answer The Question.
I leave it to you on whether you want to do the database calls using a servlet or in the JSP itself. The flow is almost the same.
First you create a class for representing the data on the UI. You have a set of (Location, Date, Planned Miles and Actual miles) and then a total of them.
You may want to create a class to represent this (I have made up the name from the id of the HTML, you may want to give a better name):
class Hike
{
private String location;
private Date date;
private Integer builtArea;
private Integer numberOfLevels;
//And their getters and setters
}
And a HikeData class
class HikeData
{
private List<Hike>;
private Integer totalBuiltArea;
private Integer totalNumberOfLevels;
//And their getters and setters
}
//The database call part is fine:
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);
//Fetch the data and populate the above classes
int totalBuiltArea = 0;
int totalNumberOfLevels = 0;
List<Hike> hikeList = new ArrayList<Hike>();
while(rs.next()){
Hike hike = new Hike();
hike.setLocation(rs.getString("location"));
hike.setDate(rs.getDate("date")));
int builtArea = rs.getInt("build_area");
hike.setBuiltArea(builtArea);
int numberOfLevels = rs.getInt("no_of_levels");
hike.setNumberOfLevels(numberOfLevels);
totalBuiltArea+= builtArea;
totalNumberOfLevels += numberOfLevels;
hikeList.add(hike);
}
HikeData hikeData = new HikeData();
hikeData.setHikeList(hikeList);
hikeData.setTotalNumberOfLevels(totalNumberOfLevels);
hikeData.setTTotalBuiltArea(totalBuiltArea);
//Add the class to request
request.setAttribute("hikeData", hikeData);
The HTML table part is now simpler:
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<%HikeData hikeData = request.getAttribute("hikeData");
for(Hike hike : hikeData.getHikeList())
{%>
<tr>
<td><%=hike.getLocation()%></td>
<td><%=hike.getDate()%></td>
<td><%=hike.getBuiltArea()%></td> //here a value comes from database
<td><%=hike.getnumberOfLevels()%></td>
</tr>
<%}>%>
<tr>
<td colspan="2">Total </td>
<td id="total_1"><%=hikeData.getTotalNumberOfLevels()%></td>
<td id="total_2"><%=hikeData.getTotalBuiltArea()%></td>
</tr>
If you are using a servlet, you move the database part to the servlet or to a service class that is called from the servlet.
If you are continuing with the JSP, you have all these in the JSP itself.
I know adding to request and then retrieving is kind of redundant but I have done so so that if you decide to move this out of the JSP, it is easier.
On a closing Note: This is definitely not the best way to write web apps. There are frameworks to make your job easier and the application maintainable and scalable. For the controller(servlet) part you can use the well known struts framework, [Spring Web flow][2], or the very simple Apache Wicket.
For the business logic part, you can use EJB3 or spring.
For database access you can use hibernate.
None of this is mandatory, but it always good to have at least a MVC framework i not the database and business logic stuff. Struts makes your life very easy.

jQuery Table Row Filtering by Column

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";
}
}
}
}

Categories