Adding ClassName of td with in the click event - javascript

I have use the following code snippet to create the tr of table in Jquery.
Code snippet:
<tr>
<td class="rowcell">
<div>
<div class="intend" style="width: 24px; height: 1px; float: left;"></div>
<div class="style='float:" left'=""></div>
<div style="width: 10px; height: 1px; float: left;"></div>
<div>Task 3</div>
</div>
</td>
<td class="rowcell">
<div>01/01/2013</div>
</td>
<td class="rowcell">
<div>01/05/2013</div>
</td><td class="rowcell">
<div>5 days</div>
</td>
<td class="rowcell">
<div>77</div>
</td>
</tr>
In this case I have invoke the click event for parent of the table. with in the click event I have use the following code snippet to change the className of td to apply the Selection Background, but ClassName cannot change in this case.
Code Snippet
//Here $ganttGridRows table rows.
var $ganttGridRows = $(this.getGanttGridTreeRows());
//Clicking in the row
var row = $target.closest('tr');
var index = $ganttGridRows.index(row);
var item = this.model.currentViewRange[recordIndex];
this.model.selectedRow = this.model.ganttRecords.indexOf(item);
var args = {};
if (this.model.selectedRow != -1)
args = { currentRowIndex: this.model.selectedRow, currrentRow: $ganttGridRows.eq(this.model.selectedRow), currentData: this.model.ganttRecords[this.model.selectedRow] };
if (this._trigger("rowSelecting", args))
return;
this.cleanUpSelection();
this._selectedRowsIndexes = [];
var cell = $target.closest('td');
//Here index is the rowindex of the selected row
$($ganttGridRows[index]).find('.rowcell').addClass("selectionbackground");
But in this did not working while using div with in the td. But if I use without div in td and directly assign the text like below code snippet and it is working fine for me.
Code Snippet
<tr>
<td class="rowcell">Task 1</td>
<td class="rowcell">01/01/2013</td>
<td class="rowcell">01/05/2013</td>
<td class="rowcell">5 days</td>
<td class="rowcell">31</td>
</tr>
Can you pleases any look in to this and provide suggestion to resolve this problem and , explain what is the reason for this behaviour.

Related

Select one data-attribute per table row and cell

I have the following html table:
<table border="1" cellpadding="5" class="test">
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">aaa</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">bbb</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">ccc</div></td>
</tr>
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">ddd</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">eee</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">fff</div></td>
</tr>
<tr>
<td class="talent-cell"><div class="btn7" data-value="0">ggg</div></td>
<td class="talent-cell"><div class="btn8" data-value="1">hhh</div></td>
<td class="talent-cell"><div class="btn9" data-value="2">iii</div></td>
</tr>
</table>
If you click on a "div attribute" inside a table cell I need to get the "data-value" of the clicked div attribute. After that I build a query string to use it with "URLSearchParams". This works so far.
Now I need a certain condition. It should be only allowed to select one div-attribute per table row and column. But I don't know how to implement this condition in my code.
This is the Fiddle and the code:
var btn7;
var btn8;
var btn9;
$('.btn7').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn7').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var7', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
$('.btn8').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn8').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var8', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
$('.btn9').click(function () {
if ($(this).attr('data-selected') === 'true') {
$(this).attr('data-selected', 'false');
$(this).removeClass('selected');
} else {
$(this).closest('tr').find('.btn9').not(this)
.removeClass('selected').attr('data-selected', 'false');
$(this).attr('data-selected', 'true');
$(this).addClass('selected');
params.set('var9', $(this).data("value"));
window.history.replaceState({}, '', `?${params}`);
}
});
const params = new URLSearchParams({
var7: btn7,
var8: btn8,
var9: btn9,
});
Idea
Mark each table cell with a data- attribute indicating its respective row and column, and maintain 2 arrays that hold the currently selected element (if any) for each of the columns and row.
Implementation
The following code implements the selection logic. Based on the arrays holding the currently active selections you can visit all relevant elements and assemble the parameters when you send a request to the server.
The specs of single cell/row selection implies that there will usually be rows and columns that do not carry a selection.
Note that the case of expressly deselecting a cell is not handled.
The code does not resort to jquery.
<!DOCTYPE html>
<html>
<head>
<title>SO _: 1-in-a-row, 1-in-a-col selection</title>
<style type="text/css">
.selected {
background: #333;
color: #fff;
}
</style>
<script type="text/javascript">
let a_colSelection = new Array(3)
, a_rowSelection = new Array(3)
;
document.addEventListener ( 'DOMContentLoaded', () => {
Array.from(document.querySelectorAll('div[data-row][data-col]')).forEach ( el => {
el.addEventListener ( 'click', eve => {
let c = parseInt(eve.target.getAttribute('data-col'))
, r = parseInt(eve.target.getAttribute('data-row'))
;
if (a_colSelection[c] !== undefined) {
document.querySelector(`div[data-col="${a_colSelection[c][1]}"][data-row="${a_colSelection[c][0]}"]`).classList.remove("selected");
}
if (a_rowSelection[r] !== undefined) {
document.querySelector(`div[data-col="${a_rowSelection[r][1]}"][data-row="${a_rowSelection[r][0]}"]`).classList.remove("selected");
}
a_colSelection[c] = [r, c];
a_rowSelection[r] = [r, c];
document.querySelector(`div[data-col="${a_colSelection[c][1]}"][data-row="${a_rowSelection[r][0]}"]`).classList.add("selected");
});
});
});
</script>
</head>
<body>
<table border="1" cellpadding="5" class="test">
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="0">aaa</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="0">bbb</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="0">ccc</div></td>
</tr>
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="1">ddd</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="1">eee</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="1">fff</div></td>
</tr>
<tr>
<td class="talent-cell"><div data-value="0" data-col="0" data-row="2">ggg</div></td>
<td class="talent-cell"><div data-value="1" data-col="1" data-row="2">hhh</div></td>
<td class="talent-cell"><div data-value="2" data-col="2" data-row="2">iii</div></td>
</tr>
</table>
</body>
</html>
Consider the following.
Fiddle: https://jsfiddle.net/Twisty/dzng31f5/39/
HTML
<table border="1" cellpadding="5" class="test">
<tr class="var7">
<td class="talent-cell">
<div class="btn" data-value="0">aaa</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">bbb</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">ccc</div>
</td>
</tr>
<tr class="var8">
<td class="talent-cell">
<div class="btn" data-value="0">ddd</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">eee</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">fff</div>
</td>
</tr>
<tr class="var9">
<td class="talent-cell">
<div class="btn" data-value="0">ggg</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="1">hhh</div>
</td>
<td class="talent-cell">
<div class="btn" data-value="2">iii</div>
</td>
</tr>
</table>
I adjusted the HTML Structure, such that each Row has a Class that represents the Index name that will be used in the Object.
jQuery
$(function() {
function checkCol(colIndex, table) {
var result = true;
console.log("Col Index:" + colIndex)
$("tbody tr", table).each(function(i, el) {
result = result && !$("td:eq(" + colIndex + ") div.btn", el).hasClass("selected");
});
return !result;
}
function checkRow(target, row) {
var isInCol = checkCol($(target).parent().index(), $(row).closest("table"));
if (!isInCol) {
if ($(".selected", row).length) {
$(".selected", row).removeClass("selected");
$(target).addClass("selected");
} else {
$(target).addClass("selected");
}
}
}
var selected = {};
$('.btn').click(function(event) {
var row = $(this).closest("tr");
checkRow(this, row);
$(".test tbody tr").each(function(i, el) {
selected[$(el).attr("class")] = $(".selected", el).length ? $(".selected", el).data("value") : "";
});
console.log(selected);
var params = new URLSearchParams(selected);
console.log(params.toString());
});
});
You can now use selected as your Data in a POST or GET call.
Updated
I had missed that each Row and Column needed to be unique. Code is updated to use Functions to check both conditions.
"Now I need a certain condition. It should be only allowed to select one div-attribute per table row and column."
The versatility of jQuery is leveraged by the use of this because it narrows down from many objects (all <td> in <table>) to a single object (<td> the user clicked). The behavior needed is common with radio button groups called "mutual exclusive selection", using .not(this) makes it simple.
In HTML,
assign a common class to each <div> (ex. '.col', see Figure I)
assign a class to each <div> that corresponds to the value of it's [data-value] (ex. '.c0', see Figure I)
Figure I
<div class='col c0' data-value='0'>
I did not include the params part in OP since it's beyond the scope of the question (see beginning of this answer). The values are stored in object C and is easily accessible (ex. C.c0).
BTW, I hope that the logic is different with your real code. For example, there is no difference between .c0 2nd row and .c0 1st row.
Details are commented in example below
// Declare object to store [data-value]
let C = {};
// Any click on a .col calls the event handler
$('.col').on('click', function() {
// Flip .selected on this .col
$(this).toggleClass('selected');
// If this .col is flipped to be .selected...
if ($(this).is('.selected')) {
//... get this .col [data-value] (0, 1, or 2)...
let idx = $(this).data('value');
/*
... find all .c0, .c1, or .c2 BUT NOT this .col and
remove .selected from them...
*/
$('.c' + idx).not(this).removeClass('selected');
/*
... then find the closest <tr>, then find all .col of
<tr> BUT NOT this .col and remove .selected from them
*/
$(this).closest('tr').find('.col')
.not(this).removeClass('selected');
// set key 'c0', 'c1', or 'c2' of C to this .col [data-value]
C['c'+idx] = $(this).data('value');
}
console.log(C);
});
<table border="1" cellpadding="5" class="test">
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
<tr>
<td><div class="col c0" data-value="0">aaa</div></td>
<td><div class="col c1" data-value="1">bbb</div></td>
<td><div class="col c2" data-value="2">ccc</div></td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Jquery append column to table

Using jQuery in a SharePoint environment, I am trying to append an object property as a last column of a table.
I am using the following JavaScript:
var id = ctx.CurrentItem.ID; //Gets IDs for items in list
console.log(id);
$(".ms-vb-lastCell").append("<td role='gridcell' class='ms-vb-cellstyle ms-vb2'>" + id + "<td>")
The DOM tree for a table row:
<tbody>
<tr class=" ms-itmHoverEnabled ms-itmhover" oncontextmenu="return ShowCallOutOrECBWrapper(this, event, false)" iid="244,1,0" id="244,1,0" role="row">
<!--iid and id are dynamically generated on load-->
<td role="gridcell" class="ms-cellstyle ms-vb2">Completed</td>
<td role="gridcell" class="ms-cellstyle ms-vb2">(2) Normal</td>
<td role="gridcell" class="ms-cellstyle ms-vb2"><span class="ms-noWrap" title="3/30/2018">3/30/2018</span></td>
<td role="gridcell" class="ms-vb-lastCell ms-cellstyle ms-vb2">
<div style="background: #F3F3F3; display:block; height: 15px; width: 120px;">
<div style="background: #00539B; height: 100%; width: 100%;"></div>
</div> 100 %
</td>
</tr>
</tbody>
How can I append each items id to the last td in each row.
You can try looping in each tr then call append on that tr object.

Selecting TD with specific classes from each TR and do math

I have a quite simple table.
Each TR with class "name-check" will be looped in php for as long as there are $name. Each new TR is getting a new class name with a counter, so basically the structures of the TR in this table looks like this:
Screenshot of table
<tr class="name-check name_1">
<tr class="name-check name_2">
<tr class="name-check name_3">
etc.
This is the content of each TR:
// Content of TR
<tr class="name-check name_1">
<td class="name">
<?php echo $name; ?>
</td>
<td class="check-date">
<label class="check-label"></label>
</td>
<td class="check-date">
<label class="check-label"></label>
</td>
<td class="check-date">
<label class="check-label"></label>
</td>
<td class="dont-count"></td>
<td class="check-date">
<label class="check-label"></label>
</td>
<td class="sum-up" align="center">
<span class="sum-up-span">0</span>
</td>
</tr>
This is the first TR which contains the TH:
// Table TH
<tr class="dates">
<th></th>
<th class="dat">1 </th>
<th class="dat">2 </th>
<th class="dat">3 </th>
<th class="dat">4 </th>
<th class="dont-count-th">Don't count</th>
</tr>
// Table TH End and after this tr comes:
<tr class="name-check name_1">...
<tr class="name-check name_2">
<tr class="name-check name_3">
When a user clicks on a TD with the class "check-date" that TD will get an extra class. Actually it is a click loop:
- 1 time click adds class .one,
- 2 time click adds class .two,
- 3 time click adds class .three.
What I want basically is, for each row, get the TD's which have any of these three classes and substract them from the number of TD's with the class of "check-date", or I could use the "TH" with class ".dat". The result should be displayed in the last td of each tr, the span with class ".sum-up-span".
I got that working for a single row, but multiple rows, it gets all the values.
var totalDays = $("tr.dates th.dat").length;
var daysOff = $("tr.name-check").each(function() {
$( "td.odsutan, td.godisnji, td.praznik" ).length;
var sum = totalDays - daysOff;
$(".sum-up-span").each(function () {
$(this).html("There " + sum + " from " + totalDays);
});
SOLVED
Both answers provided work great perfectly. Thank you guys for this.
Try this one,
$("td.check-date").click(function(e) {
if($(this).hasClass("one"))
$(this).removeClass("one").addClass("two");
else if($(this).hasClass("two"))
$(this).removeClass("two").addClass("three");
else if($(this).hasClass("three"))
$(this).removeClass("three");
else
$(this).addClass("one");
var tr = $(this).closest("tr");
var td_count = tr.find("td.check-date").length;
var clicked_td_count = tr.find("td.check-date.one, td.check-date.two, td.check-date.three").length;
tr.find("span.sum-up-span").text(td_count - clicked_td_count);
});
Your jQuery selectors are not limited to any container, so they search the entire page. What you need to do is limit them to the tr you clicked on.
Use the event e you get in a jQuery bound click function to do that:
function(e) {
var currentRow = jQuery(e.currentTarget);
var totalDays = $("tr.dates th.dat").length;
var daysOff = $("td.odsutan, td.godisnji, td.praznik", currentRow).length;
var sum = totalDays - daysOff;
$(".sum-up-span", currentRow).html("There " + sum + " from " + totalDays);
}
Note: if you don't have jQuery bound click events and need help with that, just ask.
$("table").on("click", "td.check-date", function() {
var row = $(this).closest("tr"),
checked = row.find(".one, .two, .three").length, // get the number of clicked/checked columns
toCheck = row.find(".check-date").length; // get number of columns to check
row.find(".sum-up-span").text(toCheck - checked); // print missing checks in "sum-up" column
});
// this only adds the "click" feature for a better visibility :D
(function() {
var classes = ["one", "two", "three", ""];
$("td.check-date").on("click", function() {
var td = $(this),
clicked = td.data("clicked") || 0;
td.data("clicked", clicked + 1);
this.className = "check-date " + classes[clicked % classes.length];
});
}())
td {
border: solid 1px black;
padding: 20px
}
.one { background-color: green }
.two { background-color: yellow }
.three { background-color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="name-check">
<td class="name"></td>
<td class="check-date"></td>
<td class="check-date"></td>
<td class="check-date"></td>
<td class="dont-count"></td>
<td class="check-date"></td>
<td class="sum-up" align="center">
<span class="sum-up-span">0</span>
</td>
</tr>
<tr class="name-check">
<td class="name"></td>
<td class="check-date"></td>
<td class="check-date"></td>
<td class="check-date"></td>
<td class="dont-count"></td>
<td class="check-date"></td>
<td class="sum-up" align="center">
<span class="sum-up-span">0</span>
</td>
</tr>
</tbody>
</table>

Delete table rows that are checked using one button

As the title suggests, I have created a table which I am populating with a list, and I also have a checkbox next to each element of that table. Finally I have a button labelled Delete. I want to attach that button with the actual delete operation.
Code of the button (it is inside another table):
<tr id="deleteproject" >
<td width="180" align="center" background="ButtonBackground.png"
onclick = "deleteRow('plist')">
<style="text-decoration:none; display:block; width:100%;
height:100%">
<font size="0.5px"><br/></font>
<font id="DeleteProject" face="verdana" color="white">
DELETE</font>
</a>
</td>
</tr>
The table:
<table ID="plist" border="0" cellpadding="0" cellspacing="0" datasrc="#clicklist"
style="WIDTH: 380px">
<tr>
<td id="projline" width="100%" align="left" valign="middle"
style="margin-left: 16px;">
<input type="checkbox" name="AAA"/>
<font size="3" face="Arial">
<a id="proj" href="urn:a">
<span datafld="Name"
style="margin-left: 20px; line-height: 26px;"></span>
</a>
</font>
</td>
</tr>
</table>
rowDelete function in JS:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e)
{
alert(e);
}
}
When I select a checkbox from a row and push the delete button, I get an object error, which I think means something is null or not understood in the JS code.
You must create a proper table first. The table is invalid in HTML5 and in HTML4, the button needs to be inside a table. Please read this article.
When I select a checkbox from a row and push the delete button, I get an object error, which I think means something is null or not understood in the JS code.
I don't know where to start ... looking at the JS, you are trying to target rows by referencing them by the TableRow Object? or ChildNode? Either way, the vague error message you are receiving is because you must reference the elements in the DOM as an object. There are several ways to do so in your situation, for example:
The tr needs to be referenced by what they are: <tr> the tag name.
var All_TR_Tags = document.getElementsByTagName('tr');
Now All_TR_Tags is an array-like object
Please review the demo and ask questions because I can't make a list of what is wrong and what issues that need to be addressed because it would take hours. The demo's styling is not part of the topic, I just used it because it's a default style I use for tables. The structure of the table is important as much as the JS though. The source itself has been extensively annotated. Please do not hesitate to ask if you have any further questions.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>delRows</title>
<style>
.x th {
color: #FFF;
background: #2C7EDB;
padding: 10px;
text-align: center;
vertical-align: middle;
}
.x tr:nth-child(odd) {
background-color: #333;
color: #FFF;
}
.x tr:nth-child(even) {
background-color: #D3E9FF;
color: #333;
}
.x td {
border-style: solid;
border-width: 1px;
border-color: #264D73;
padding: 5px;
text-align: left;
vertical-align: top;
position: relative;
}
.x thead th:first-child {
border-top-left-radius: 6px;
}
.x thead th:last-child {
border-top-right-radius: 6px;
}
.x tbody tr:last-child th:first-child {
border-bottom-left-radius: 6px;
}
.x tbody tr:last-child td:last-child {
border-bottom-right-radius: 6px;
}
th {
width: 30%;
}
th:first-of-type {
width: 10%;
}
table {
width: 80%;
}
</style>
</head>
<body>
<table id="T1" class="x">
<thead>
<tr>
<th>
<input id="btn1" type="button" value="DelRows" onclick="delRows('T1')" )/>
</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr id="row1">
<td>
<input id="chx1" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row2">
<td>
<input id="chx2" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row3">
<td>
<input id="chx3" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row4">
<td>
<input id="chx4" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row5">
<td>
<input id="chx5" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row6">
<td>
<input id="chx6" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row7">
<td>
<input id="chx7" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row8">
<td>
<input id="chx8" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row9">
<td>
<input id="chx9" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr id="row10">
<td>
<input id="chx10" type="checkbox" />
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<script>
function delRows(tableID) {
//1| Take the function's argument and reference it as an id.
var table = document.getElementById(tableID);
//2| getElementsByTagName()[0]¹ will find the first† element with the <tbody> tag.
/* †You can use [0] to specify the first tag, [1] for the second tag, etc. <tbody> is the direct parent of all <tr>, so that's why we want a reference to it */
var tb = table.getElementsByTagName('tbody')[0];
//3| Collect all checkboxes that are checked into a NodeList² named 'checked'.
/* querySelectorAll³ is like getElementBy* on steroids. It accepts a selector as a target to reference, the syntax is like CSS or inside a jQuery object $(selector). Notice the ":checked"⁴ pseudoselector */
var checked = document.querySelectorAll('input[type="checkbox"]:checked');
//4| Collect all <tr> in <tbody> into a NodeList named 'rows'.
/* Remember we referenced the <tbody> as var tb on step 2? */
var rows = tb.querySelectorAll('tr');
//5| Iterate through the checked NodeList from step 3.
/* When dealing with arrays and array-like objects, you'll need to use a 'for loop' to iterate (or loop)⁵ 90% of the time. */
for (var i = 0; i < checked.length; i++) {
//6| For every checked checkbox find it's parent's parent and name it 'row'.
/* In the checked NodeList, there are all of the checked checkboxes so on each loop we are finding that particular checkbox's "grandmother". Example:
i = 4 means we are on the 3rd iteration (loop).
checked[4] is the third checked checkbox.
.parentNode⁶ is the parent element of the third checked checkbox--a <td>
The second .parentNode is the parent of the <td> which is a <tr> */
var row = checked[i].parentNode.parentNode;
//7| Remove 'row' from <tbody>
/* removeChild⁷ needs the parent of the element (or node) that you intend to remove. Thinking ahead, we have the parent of all <tr>: tb (a.k.a. <tbody>) from step 2. */
tb.removeChild(row);
//8| At this point, i is i+1 we go back to step 5 as long as "i < checked.length".
/* var i = one loop of steps 6, 7, and 8. It started initially as 0 which by design coincides with the 0 count index of arrays and array-like objects like the NodeList checked. i is then incremented by 1 (i++) thereby completing the loop. As long as i is less than the total amount of checked checkboxes, it will continue looping. */
}
//9| At this point, i is greater than the total amount of checked checkboxes and stops looping thru steps 6, 7, and 8.
/* This is the end of the function. Sometimes you'll see "return false;", but we didn't need it because the click event that starts this function is just a button. If we kept the original markup, that used an anchor, then "return false" would be necessary because an anchor by default will jump to a location which is undesirable if you are using the anchor as a button instead. */
}
</script>
</body>
</html>

Using slideToggle with table rows (nesting a div) not working

After reading around it seems that a good solution to using slideToggle() on table rows is to nest a div inside. I've tried the following, but it doesn't seem to work at all.
jQuery
function toggle_dropdown(entry_id) {
$(".library-dropdown-animation").slideUp("slow"); // Slide up any that are open
$(".library-edit-dropdown").style.display = "none"; // Set their table row displays to none
$("#library-dropdown-animation-" + entry_id ).slideDown("slow"); // slide the clicked one down
$("#library-edit-dropdown" + entry_id ).style.display = "block"; // set it's parent table row's display to block
}
HTML
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(123);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-123" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-123">
</div>
</td>
</tr>
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(124);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-124" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-124">
</div>
</td>
</tr>
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(125);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-125" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-125">
</div>
</td>
</tr>
So essentially, I've got a td in another row that when it's clicked it slides it's content row (right beneath it) down while sliding any other row up. Since we can't use slide on table row (hide() and show() and toggle() works perfectly fine by the way) i've used a containing div that has content, in this example i've left the content out. In any case, clicking on the td does nothing using this jQuery.
Here is a jsFiddle: http://jsfiddle.net/wxu3E/
Please check this solution: http://jsfiddle.net/wxu3E/2/
i added the events on the Anchor itself not the row by adding a class to it, also I added attribute entry_id
Click
and in the JQuery code the event will be attached to elements with class toggle_dropdown
$(".toggle_dropdown").click
Working Jsfiddle: http://jsfiddle.net/patelmilanb1/LzaZT/
Suggestion: data-attributes might come in handy here... i have added data-attribute in your HTML, please look at the HTML carefully in jsfiddle.
data-id="123"
so your final Jquery looks like this:
$(document).on("click", ".library-item-title", function (e) {
e.preventDefault();
var entry_id = $(this).data("id");
toggleDropdown(entry_id);
});
function toggleDropdown(entry_id) {
$(".library-edit-dropdown").slideUp("slow");
$("#library-edit-dropdown-" + entry_id).slideDown("slow");
}
Error in your code: you are missing - at the end in this line, as your DIV id deos contain -
$("#library-edit-dropdown" + entry_id ).style.display = "block";
try this fiddle for animation: http://jsfiddle.net/patelmilanb1/LzaZT/1/
function toggleDropdown(entry_id) {
$(".library-edit-dropdown").hide("slow");
$("#library-edit-dropdown-" + entry_id).show("slow");
}

Categories