target the parent row of a particular cell - javascript

I have a table with a list of records. each row has class "list_request" and has a cell of class "record_approval":
<table>
<tr>
<th>name</th><th>date</th><th>id</th><th>group</th><th>approval</th>
<tr class="list_request">
<td>Frank</td><td>2012-2-15</td><td>01</td><td>Account</td><td class="record_approval">Dave Ellis</td>
</tr>
<tr class="list_request">
<td>Ellen</td><td>2012-2-19</td><td>04</td><td>Admin</td><td class="record_approval">Susan Peters</td>
</tr>
<tr class="list_request">
<td>Michael</td><td>2012-2-26</td><td>06</td><td>Admin</td><td class="record_approval"></td>
</tr>
I'd like to construct a javascript function that checks whether or not "record_approval" has a value (which value is unimportant), and if so, change the css color value for that row. Essentially, the approved records should have a different color than the unapproved ones.
something like...
function check_approval(){
var checkrow = document.querySelectorAll( "tr.request_list" )
var checkcell = document.querySelectorAll( "td.record_approval" )
for (i=0;i<checkcell.length;i++){
if (!checkcell.value){
this.parentNode.style.color = "ff9900";
}
else{
}
}
is this essentially the wrong approach?

Mistakes I found:
Unclosed for loop (missing closing })
You're looking for class request_list, but on your html it's list_request
You should be using checkcell[i] instead of checkcell inside your loop
Your color hex value should begin with a #.
There's no need to get all rows and cells from an event listener
It's unclear when you want that function to run. Should it respond to an event?
Also, I'd set a new css class on the row, instead of setting the color directly.
Apparently, you're looking for this:
var checkcell = document.querySelectorAll( "td.record_approval" );
for (i=0;i<checkcell.length;i++){
if (checkcell[i].innerHTML){
checkcell[i].parentNode.style.color = "#ff9900";
}
}
http://jsbin.com/anadij/1/edit

checkcell is an array of elements. you'll want to loop through them, accessing 'checkcell[i]' instead of checkcell.value.
your hex color should be defined with a "#" preceding ff9900
your for loop isn't closed properly
basically update it s.t.
if (!checkcell[i].value){
checkcell[i].parentNode.style.color = "#ff9900";
} else{
}

Related

Showing Hidden Row in Table

I am using some code based on the following JSFiddle. The intention is to show more information when the user clicks the "Show Extra" link.
The problem that I'm having is that when the link is clicked on all but the bottom row of the table the hidden element is shown briefly and then closes.
I am populating my table using template strings in javascript. Here is the code that I use to add rows to the table:
this.addRecordToTable = function(bet, index, id){
console.log(index);
console.log($.data(bet));
var butId = id.toString();
if (bet.bookies == null){
bet.bookies = "";
}
if (bet.bet == null){
bet.bet = "";
}
var newRow = `
<tr>
<td>${bet.date}</td>
<td>${bet.bookies}</td>
<td>${bet.profit}</td>
<td><button id=${butId}>Delete</button></td>
<td>Show Extra</td>
</tr>
<tr>
<td colspan=\"5\">
<div id=\"extra_${index}\" style=\"display: none;\">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
`
console.log(newRow);
console.log("#"+butId);
$(newRow).appendTo($("#betTable"));
$("#"+butId).click(
function()
{
if (window.confirm("Are you sure you want to delete this record?"))
{
var rec = new Records();
rec.removeRecordAt(index);
$("#betTable tbody").remove();
var c = new Controller();
c.init();
}
});
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
}
EDIT:
I had to change $("a[id^=show_]").click to $("a[id=show_"+index).click..., as the event handler was being added to each element every time I added a new element. Thanks to #freedomn-m.
This code:
$("a[id^=show_]")
adds a new event handler to every existing link as well as the new one as it's not ID/context specific so all the show a's match the selector.
You need to add the context (newRow) or use the existing variable(s) as part of the loop that are already defined, eg:
$("a[id^=show_]", newRow)
$("a#show_" + index)
(or any other variation that works).
An alternative would be to use even delegation for the dynamically added elements, eg:
$(document).on("click", "a[id^=show_]", function...
in which case you'd only need to define/call the event once and it would be fired for new elements (ie put that outside the new row loop).

Delete DOM elements throught loop

I am trying to create a loop which is reponsible to delete DOM elements (one or severals lines into an HTML table) :
<tr class="entireLine><input type="checkbox"></tr>
<tr class="entireLine><input type="checkbox" checked></tr>
<tr class="entireLine><input type="checkbox" checked></tr>
JS
for (var i=0; i<$(".entireLine").length; i++){
// Get the current line of the table
var currentLine = $(".entireLine")[i];
// Get the checkbox in the DOM element
var checkbox = $(currentLine).find("input[type=checkbox]");
// Check the state of the checkbox. If checked, remove the line.
if ( $(checkbox).is(":checked") ) {
$(currentLine).remove();
}
}
This code works fine only when there is one line selected. From 2 lines selected, the second line is not deleted because the index (i) is not good after the first remove.
Where is my mistake ?
You can just find tr with checked checkboxes
$(".entireLine").has('input[type=checkbox]:checked').remove()
In your loop the problem is the expression $(".entireLine").length is evaluated in each iteration, it will reduce the length if item was removed in the previous iteration but the value of i is not reduced so there will be some leftout items
.has()
:checked
Use a jquery each:
$(".entireLine").each(function( index ) {
if ($(this).find("input[type=checkbox]").is(":checked")) {
$(this).remove();
}
});
And correct your HTML, it's not <tr class="entireLine> but <tr class="entireLine"> (You forget the closing ")
Reverse your thinking - instead of looping through all the rows to find selected items, find the selected items then remove their rows:
$(":checkbox:selected").each(function() {
$(this).closest("tr").remove();
});
I would do something like this, instead of doing the for loop. This will find all the checkboxes, and do a $.each and if they are checked, it will remove them. I put checkboxes in its own var for debugging purposes.
var checkboxes = $('input[type=checkbox]');
checkboxes.each(function(){
var $checkbox = $(this);
if ( $checkbox.is(":checked") ) {
$checkbox.remove();
}
})

Trying to remove a child html element with javascript

I have 3 tables in my boostrap tab. Each tab as a table. The rows of this table is dynamically generated with csharp asp.net code. Right I Want a scenario were if a user click on the row of the first table, the clicked role of the first table get remove from the first table and is added to the rows of the second table.
My challenge as been getting to remove the row after the onClick process.
<tbody>
<tr id="kayode#yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515"
data-parentid="kayode#yahoo.com"
href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com"
operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Active</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>02:52:55</td>
<td>271.0.0.1</td>
</tr>
</tbody>
My javascript code which I am trying to use to remove the row after the Click event.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
//alert(parentid);
//we are going to remove the role from this field
var element = document.getElementById(parentid);
element.parentNode.removeChild(element); //This line is a problem says
//document.querySelector("tablebody4 first").appendChild(element);
console.log(element);
}
This is untested, but I imagine jQuery will greatly reduce your headache here:
function updateWaitingState(sender) {
var parentId = $(sender).attr("data-parentid");
$('#' + parentId).appendTo('.tablebody4:first');
}
You may need to adjust the selector in the appendTo function, as it was a guess on my part.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
var element = document.getElementById(parentid);
$(element).appendTo('.tablebody2:first');
}

Selecting a random HTML element using JavaScript only

I'm trying to select an element from my HTML code, to then use it in JavaScript (it needs to be highlighted). The HTML consists of a table with 36 td's.
My code so far:
var box;
function getRandom()
{
return (Math.floor(Math.random()*37))
}
function highlight()
{
box = document.getElementById(getRandom());
box.style.backgroundColor = "yellow";
}
If anyone can give me any pointers, it'd be appreciated. I know it would be easy using jQuery, but I haven't begun learning that yet.
Edit: excerpt of the HTML code, this goes up to name="36".
<table id="reflexTable">
<tbody>
<tr>
<td name="1"></td>
<td name="2"></td>
<td name="3"></td>
<td name="4"></td>
<td name="5"></td>
<td name="6"></td>
</tr>
A nicer way that does not involve setting element ids:
function highlight() {
// get all TDs that are descendants of table#reflexTable:
var tds = document.getElementById('reflexTable').getElementsByTagName('td');
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight td at that index
tds[rand].style.backgroundColor = "yellow";
}
The big advantage of this method is that you can add/remove as many TDs as you please without needing to edit your JS to generate a valid random number.
getElementById gets the element which has the matching id. Your table data cells don't have an id at all. They have a name, but HTML doesn't allow that.
Switch to id.
HTML 4 doesn't allow an id to start with a number. Prefix the id with a common string. Then:
document.getElementById("foo" + getRandom());
You're not setting the id attribute, you're setting the name attribute, change it to:
<td id="1"></td>
...etc
Several things:
You should declare the box variable inside the highlight function.
You have to convert that random number to a string.
Quentin mentioned something important--you should give each table element an id of something like "s0","s1","s2", etc...
Start the naming at 0 because your getRandom function will sometimes return it.
function highlight(){
var number;
number = getRandom().toString();
var box;
box = document.getElementById("s" + number);
box.style.backgroundColor = "yellow";
}

odd even class for table rows

I have table with rows where as in between have hidden rows and because of that odd even css class not able to set. How can I avoid those hidden rows?
HTML
<tr class="oddRow">
<td>Avinash</td>
<td>18-Jun-2010</td>
<td>LI1004</td>
<td>5,600.00</td>
<td>Sort</td>
</tr><tr class="oddRow" style="display:none;">
<td>Ajith</td>
<td>18-Jun-2010</td>
<td>LI1006</td>
<td>5,001.00</td>
<td>!</td>
</tr><tr class="evenRow">
<td>Ankur</td>
<td>14-Jun-2010</td>
<td>LI1005</td>
<td>5,000.00</td>
<td>me</td>
</tr><tr class="oddRow">
<td>Ajith</td>
<td>18-Jun-2010</td>
<td>LI1006</td>
<td>5,001.00</td>
<td>!</td>
</tr>
I know this isn't tagged jQuery but this would be the easiest way to apply this solution...
You don't need two CSS classes here (odd and even), just one. Start by setting the CSS for every row to use the "oddRow" style declarations by default. The "evenRow" style declarations should simply overwrite the defaults.
Add this JS function
var zebraStripes = function($) {
$('table.stripes tr').removeClass('evenRow')
.filter(':visible:odd').addClass('evenRow');
// using the :odd selector as it is zero-based
}
You can then bind this function to the document ready event as well as any event that changes row visibility.
Edit
Updated to work with jQuery 1.7, example here - http://jsfiddle.net/UZNKE/6/
Assuming your question is asking what I posted in the comments, you'll have to have a more in-depth 'hide' function which will change the classes of all subsequent functions. I expect you'll want to use something like this:
function hideRow(rowNum)
{
var rows = document.getElementById('table-id').getElementsByTagName('table');
// get current class and hide the row
var currentClass = rows[rowNum].className;
rows[rowNum].style.display = 'none';
// set up classname array
var classNames = new Array("oddRow", "evenRow");
// make sure 'j' points to the next desired classname
var j = 0;
if (classNames[j] == currentClass)
j = 1;
// make all subsequent visible rows alternate
for (i=rowNum+1; i<rows.length; i++)
{
// ignore empty rows
if (rows[i].currentStyle.display == "none")
continue;
// set class name
rows[i].className = classNames[j];
j = (j+1) % 2;
}
}
Note: I haven't tested the code, but I commented it so you should be able to figure out what's going on

Categories