Looping through table rows with Javascript/Jquery - javascript

So what I'm trying to do is get the last row of an HTML table. If this row then has a certain class I will ignore this row and select the previous one. This would then be cycled through from the end of the table until a row was found without this certain class.
I figured it's probably involving a for loop, a check for the row class and then JQuery's row.prev method, but still not quite sure how to approach this.
Thanks in advance!

To get the last table row that doesn't have a certain class, say targetClass, you can do this:
$("tr:not(.targetClass):last");
I'm not sure what you want to do with this table row, but if you were to add targetClass to the last row that didn't have it, it would look like this
$("tr:not(.targetClass):last").addClass("targetClass");
Check out this fiddle to see it in action

This example shows you how to get the last of each table on the current page: http://jsfiddle.net/JBnzK/
$('table').find('tr:last').each(function(){
if ($(this).hasClass('stupid')) {
$(this).css('color', 'red');
} else {
$(this).css('color', 'green');
}
});

Assuming you've got the following HTML:
<table id="mytable">
<tbody>
<tr>
<td>1</td>
</tr>
<tr id="YouFoundMe">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
</tbody>
</table>
You can do this:
var elWithoutClass = $('#mytable tr:not(.certainclass):last');
if (elWithoutClass.length) {
alert(elWithoutClass.get(0).id);
// alerts "YouFoundMe"
}
:not(.certainclass) will eliminate <tr> without class 'certainclass'
:last will get you the last one
I invite you to check the Selectors documentation page of jquery to learn more about them.

Related

How to create an html table with data that can change using JS

I'm trying to create an online calculator, using a table, with a tag that will have an output that changes. The output is the result of whatever math function is used on the calculator. So if someone puts in 5*5, the th should show 25. I tried using a variable, output, in javascript, and then using document.getElementsByTagName("th").innerHTML(output), to have it changing, but that didn't work. Then I tried the same command without a variable, and instead just directly inserting a string in the innerHTML and it still wasn't working. I also tried write(), but that didn't work either. Any ideas on what I can try?
This is my table (the id's and classes are just some style attributes in my css file):
<table class="center" style = "width:20%">
<tr>
<th colspan="4" id = "final">0</th>
</tr>
<tr id = "opRow">
<td>+</td>
<td>-</td>
<td>x</td>
<td>/</td>
</tr>
<tr class = "dataRow">
<td>7</td>
<td>8</td>
<td>9</td>
<td rowspan = "4" id = "eqBut">=</td>
</tr>
<tr class = "dataRow">
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr class = "dataRow">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr class = "dataRow">
<td style = "width:26%" id = "acBut">ac</td>
<td>0</td>
<td>.</td>
</tr>
</table>
getElementsByTagName() returns an array and so you'll have to reference it like this:
document.getElementsByTagName("th")[0]
assuming that you only have 1 th tag on your current page.
plus innerHTML is a property of an element and not a method, so you'll have to rewrite:
document.getElementsByTagName("th")[0].innerHTML = output
Also, your current implementation should be throwing some errors in your browser console log please do check it out.
Method / function
getElementsByTagName
is returning an array with all available tags from your html, then you've only 1 th in your table so is result the th tag from your table is first [0], now use method mention to select th tag and select first element [0]
innerHTML - used to rewrite data as I know
and use it to rewrite cell.
So use that :
document.getElementsByTagName("th")[0].innerHTML = 52;
To check if is working try this :
document.addEventListener("DOMContentLoaded", function(){
document.getElementsByTagName("th")[0].innerHTML = 52;
});
Well, I hope that you understand what I want to say. Thanks.

Finding a certain number in html and replace it with custom text

So, I have a table and there is a colum called value with different numbers that varies from 0 to 2.
<column>Values<column>
<td>0</td>
<td>2</td>
<td>0</td>
Yes, I know that something like does not exist, it was just for sake of example.
But the real question is, how can I with help of jquery find those numbers and replace it with something else.. for example
if(td == 1){
replace 1 with "Hello"
}
Use contains() to get td which have similar text and replace text using .text()
$("td:contains('1')").text("hello");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
Well, it depends...
If you are refering to ALL the content of the cell as a numeric value, you can do this (in JS)
if(Number($(td).html().trim()) == number_to_replace){
$(td).html(text_for_replacement);
}
where "td" could referer to the cell as a DOM variable or could be a string selector
Can you give your elements Id's? This may make your code more readable and maintainable, and will remove the dependency between the value you are trying to replace and the code that is looking for it.
If you can use Id's, then you can use jQuery selectors to get hold of the element and then, depending on the element type, set the text or innerHtml to your required values.
Foe example;
$( document ).ready(function() {
$('#col1').text('hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td id="col1">1</td>
<td id="col2">2</td>
<td id="col3">3</td>
</tr>
</table>
or JsFiddle.net
Use :contains() pseudo-class to select all td which contains 1 and then use text() with callback to check content is exactly 1 and update.
$('td:contains(1)').text(function(i, v) {
return $.trim(v) == '1' ? 'hello' : v;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>11</td>
</tr>
</table>

How to insert markup into a table using javascript

I have a table row with four cells. I'm trying to use javascript to insert this:
</tr><tr>
in between two cells which would basically create two rows from one (at certain screen sizes).
I need to change this:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
into this:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
</tr><tr>
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
Here is my script:
$('table tr td:nth-child(3)').before('</tr><tr>');
And here is what I get:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
<tr></tr> <--- notice that </tr><tr> becomes <tr></tr>!
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
The tags are appearing in the right place, but they are switched around!
What the heck is going on here? Can anyone please help?
Despite the abstraction offered by jQuery, you are not working with HTML. You are working with DOM objects.
"</tr><tr>" gets interpreted as:
End tag for table row which doesn't exist, ignore this
Create a table row
You need to create a table row, put it where you want it to be and then move the table cells into it.
Possibly like this:
var tr = $('<tr />');
tr.append($('td+td+td'));
$('table').append(tr);
You could add another row and transfer the last two td elements to the new row.
$('<tr>').insertAfter('tr').append($('td').slice(-2))
http://jsfiddle.net/g9xnsus5/2/

Show/Hide Table Rows using Javascript classes

I have a table that kind of expands and collapses, but it's getting too messy to use it and IE and Firefox are not working properly with it.
So, here's the JavaScript code:
function toggle_it(itemID){
// Toggle visibility between none and ''
if ((document.getElementById(itemID).style.display == 'none')) {
document.getElementById(itemID).style.display = ''
event.preventDefault()
} else {
document.getElementById(itemID).style.display = 'none';
event.preventDefault()
}
}
And a Sample HTML:
<table>
<tr>
<td>Product</td>
<td>Price</td>
<td>Destination</td>
<td>Updated on</td>
</tr>
<tr>
<td>Oranges</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr id="tr1" style="display:none">
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr id="tr2" style="display:none">
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr>
<td>Apples</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr id="tr3" style="display:none">
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr id="tr4" style="display:none">
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
</table>
The problem is that I use one ID for each and every and that's very annoying because I want to have a lot of hidden rows for each parent and a lot of parents, so it would be too many IDs to handle. And IE and FireFox are only showing the first Hidden Row and not the others. I suspect this happens because I've made it work by triggering all IDs together.
I think it would be better if I use Classes instead of IDs to indetify the hidden rows.
I'm really new to all of this so please try and explaining it in any kind of simply way. Also I've tried jQuery but wasn't able to get it.
It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.
Here's the fiddle: link.
What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".
I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.
$(".toggler").click(function(e){
// you handle the event here
});
With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)
In the event handler, I do this:
$('.cat'+$(this).attr('data-prod-cat')).toggle();
With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).
I hope this was explanatory enough.
Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:
<table id="products">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Destination</th>
<th>Updated on</th>
</tr>
</thead>
<tbody>
<tr class="parent">
<td>Oranges</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
...etc.
</tbody>
</table>
And then have some CSS that hides all non-parents:
tbody tr {
display : none; // default is hidden
}
tr.parent {
display : table-row; // parents are shown
}
tr.open {
display : table-row; // class to be given to "open" child rows
}
That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.
With jQuery you can then simply do this:
// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
// prevent default behaviour
e.preventDefault();
// find all the following TR elements up to the next "parent"
// and toggle their "open" class
$(this).closest("tr").nextUntil(".parent").toggleClass("open");
});
Demo: http://jsfiddle.net/CBLWS/1/
Or, to implement something like that in plain JavaScript, perhaps something like the following:
document.getElementById("products").addEventListener("click", function(e) {
// if clicked item is an anchor
if (e.target.tagName === "A") {
e.preventDefault();
// get reference to anchor's parent TR
var row = e.target.parentNode.parentNode;
// loop through all of the following TRs until the next parent is found
while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
toggle_it(row);
}
});
function nextTr(row) {
// find next sibling that is an element (skip text nodes, etc.)
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
function toggle_it(item){
if (/\bopen\b/.test(item.className)) // if item already has the class
item.className = item.className.replace(/\bopen\b/," "); // remove it
else // otherwise
item.className += " open"; // add it
}
Demo: http://jsfiddle.net/CBLWS/
Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
w3cSchool link to JQuery show and hide
event.preventDefault()
Doesn't work in all browsers. Instead you could return false in OnClick event.
onClick="toggle_it('tr1');toggle_it('tr2'); return false;">
Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.
Below is my Script which show/hide table row with id "agencyrow".
<script type="text/javascript">
function showhiderow() {
if (document.getElementById("<%=RadioButton1.ClientID %>").checked == true) {
document.getElementById("agencyrow").style.display = '';
} else {
document.getElementById("agencyrow").style.display = 'none';
}
}
</script>
Just call function showhiderow()upon radiobutton onClick event
AngularJS directives ng-show, ng-hide allows to display and hide a row:
<tr ng-show="rw.isExpanded">
</tr>
A row will be visible when rw.isExpanded == true and hidden when
rw.isExpanded == false.
ng-hide performs the same task but requires inverse condition.

Hide table row if one of its columns is empty using CSS [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
hide row if it contains empty columns
Can the row containing empty cell in this table be hidden using CSS.. I have tried jQuery and its not working right now..
this is what I used and it doesn't do anything!
$('.EventDetail tr').each(function(){
if ($('td:empty',this).length > 0))
$(this).hide();
});
There ain't nothing wrong with this piece of jQuery, is there? I would like to see if we can do display:none for the selected row? Is it something achievable using CSS?
<table cellpadding="10" class ="EventDetail">
<tr>
<td class="TableFields"><em>Who Should Enroll?:</em></td>
<td>Everyone 18 and older who would like to attend</td>
</tr>
<tr>
<td class="TableFields"><em>Handicapped Access:</em></td>
<td>Yes</td>
</tr>
<tr>
<td class="TableFields"><em>Parking Notes:</em></td>
<td></td>
</tr>
<tr>
<td class="TableFields"><em>Instructor:</em></td>
<td>John Filler</td>
</tr>
</table>
This selector should do it...
$('.EventDetail tr:has(td:empty)').hide();
jsFiddle.
The :empty selector looks for elements with no child nodes. If it is possible you may have whitespace there, but you still consider it empty, try something such as...
$('.EventDetail tr').filter(function() {
return $(this).find('td').filter(function() {
return ! $.trim($(this).text());
}).length;
}).hide();
jsFiddle.

Categories

Resources