I have a problem regarding jQuery selector, where I have a Table structure as below (HTML Portion), and there is a link in table column for click and move the Table Row "UP" and "Down" by using jQuery (jQuery Portion, reference from this post).
jQuery Portion :
$(".up,.down").click(function() {
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev("tr:has(td)"));
} else {
row.insertAfter(row.next());
}
});
HTML Portion :
<table cellspacing="0" border="0" id="Table1" style="text-align:center" >
<tr>
<th scope="col" width="80px">Column A</th><th scope="col" width="80px">Column B</th><th scope="col"> </th>
</tr>
<tr>
<td>
<span id="GridView1_ctl02_lbl1">A</span>
</td><td>
<span id="GridView1_ctl02_lbl2">0</span>
</td><td>
Up Down
</td>
</tr><tr>
<td>
<span id="GridView1_ctl03_lbl1">B</span>
</td><td>
<span id="GridView1_ctl03_lbl2">2</span>
</td><td>
Up Down
</td>
</tr><tr>
<td>
<span id="GridView1_ctl04_lbl1">C</span>
</td><td>
<span id="GridView1_ctl04_lbl2">2</span>
</td><td>
</td>
</tr><tr>
<td>
<span id="GridView1_ctl05_lbl1">D</span>
</td><td>
<span id="GridView1_ctl05_lbl2">2</span>
</td><td>
</td>
</tr><tr>
<td>
<span id="GridView1_ctl06_lbl1">E</span>
</td><td>
<span id="GridView1_ctl06_lbl2">3</span>
</td><td>
Up Down
</td>
</tr>
</table>
I wanted the Row to be move "UP" and "Down" group by values in "Column B" (as per highlighted with red box") instead of ordinary row by row. Based on example of the diagram, the moving of rows should be move by the red boxes.
So my question is, how can I using jQuery selector to select rows group by value in "Column B"? which the onclick event was trigger on links ("Up" & "Down") click.
Thank you in advanced :)
I don't think you can do this with Just selectors and a single command! but you can use some loops :
$(".up,.down").click(function () {
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
myRow = row;
prevRow = row.prev("tr");
currentValue = myRow.children("td").eq(1).text();
prevValue = prevRow.children("td").eq(1).text();
parNode = myRow.parent();
i = 0;
family = [];
parNode.children("tr").each(function(){
if($(this).children("td").eq(1).text() == currentValue){
family[i] = $(this);
i++;
}
});
for(var j = 0; j <= i; j++ ){
while(prevRow.children("td").eq(1).text() == prevValue){
prevRow = prevRow.prev("tr");
}
family[j].insertAfter(prevRow);
}
} else {
row.insertAfter(row.next());
}
});
Demo here: http://jsfiddle.net/shahverdy/PSDEs/2/
In this demo I implemented only Up. Click Up for values 2 and 3 to see how it works.
Given the table structure above, you can make a map storing (value in column b, corresponding tr array) pairs, if all the rows that have the same value in column B are adjacent. And when you click the Up/Down link, detach all the rows with the same value and get the rows above (for Up) or bellow (for Down). Then you know where to attach those detached rows.
$(function() {
var column_index = 1;
function get_value(tr) {
return $('td', tr).eq(column_index).text().trim();
}
function group_by(trs, column_index) {
var map = {};
trs.each(function (idx) {
var value = get_value($(this));
if (map[value])
map[value].push($(this));
else
map[value] = [$(this)];
});
return map;
}
var map = group_by($('#Table1 tr:gt(0)'), column_index);
$('a.up').click(function () {
var tr = $(this).closest('tr');
var value = get_value(tr);
var group = map[value];
var prev = group[0].prev('tr');
if (prev.length == 0 || $('th', prev).length != 0)
return;
var prev_value = get_value(prev);
var prev_group = map[prev_value];
for (var i = 0; i < group.length; i++) {
group[i].detach();
prev_group[0].before(group[i]);
}
});
$('a.down').click(function () {
var tr = $(this).closest('tr');
var value = get_value(tr);
var group = map[value];
var next = group[group.length - 1].next('tr');
if (next.length == 0)
return;
var next_value = get_value(next);
var next_group = map[next_value];
for (var i = group.length - 1; i >= 0; i--) {
group[i].detach();
next_group[next_group.length - 1].after(group[i]);
}
});
});
Refer to the code example at jsFiddle.
If you generate the table dynamically at the server end, it would be better to do the group with SQL or server end languages, and attach some class to the tr to identify the groups.
Related
So pretty much I have it to were it's searching for the innerHTML of the td in question in each row....however I'm trying to grab the input name attribute from below
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
Here's what i have so far
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 ||
(v.length < 3 && fullname.indexOf(v) == 0) ||
(v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
var n = document.getElementById("noresults");
if (on == 0 && n) {
n.style.display = "";
document.getElementById("qt").innerHTML = q.value;
} else {
n.style.display = "none";
}
However right now it's only indicating within the td.... How do I get the above to look for the name of the input inside of the td?
Much appreciated.
You don't need a lot of code for that. On most modern browser this works.
//For 1 value
myInput = document.querySelector('#tablename td [name="Client"]');
console.log(myInput);
//For more values
myInput2 = document.querySelectorAll('#tablename td [name="Client"]');
console.log(myInput2); //it's an array now
//Like this?
myInput3 = document.querySelector('#tablename td [name]');
if(myInput3.getAttribute('name') == 'Client'){
myInput3.setAttribute('name', 'something');
}
console.log(myInput3.parentElement);
<table id="tablename">
<tr>
<td><input name="Client"></td>
</tr>
</table>
If you have a reference to the <td> element, you can use querySelector to get a reference to the <input> (assuming it's the only or first <input> descendant) and then getAttribute to get the value of the name attribute:
// You already have a reference to the <td>
const td = document.querySelector('td');
// Get the <input>
const input = td.querySelector('input');
// Get its `name` attribute
const name = input.getAttribute('name');
console.log('name is "%s"', name);
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
Right now I have code that can filter by int:
<input name='tablefilter' type='checkbox' value='1' id='tablefilter1' checked/>
<label for='tablefilter1'>1</label>
<input name='tablefilter' type='checkbox' value='2' id='tablefilter2' checked/>
<label for='tablefilter2'>2</label>
<input name='tablefilter' type='checkbox' value='3' id='tablefilter3' checked/>
<label for='tablefilter3'>3</label>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody id='tablebody'>
<tr>
<td>1</td>
<td>One</td>
<td>First</td>
</tr>
<tr>
<td>2</td>
<td>Two</td>
<td>Second</td>
</tr>
<tr>
<td>3</td>
<td>Three</td>
<td>Third</td>
</tr>
</tbody>
</table>
js
/* Demo filtering table using checkboxes. Filters against first td value */
/* Set 'ready' handler' */
document.addEventListener('DOMContentLoaded', initFunc);
/* When document ready, set click handlers for the filter boxes */
function initFunc(event) {
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
filters[i].addEventListener('click', buildAndExecFilter);
}
}
/*
This function gets called when clicking on table filter checkboxes.
It builds a list of selected values and then filters the table based on that
*/
function buildAndExecFilter() {
var show = [];
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
if (filters[i].checked) {
show.push(filters[i].value);
}
}
execFilter(show); // Filter based on selected values
}
function execFilter(show) {
/* For all rows of table, see if td 0 contains a selected value to filter */
var rows = document.getElementById('tablebody').getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var display = ""; // Default to display
// If it is not found in the selected filter values, don't show it
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
// Update the display accordingly
rows[i].style.display = display;
}
}
http://jsfiddle.net/2Lm7pytt/3/
However that filter can't filter by a string. If I for example want to use "one" instead of 1, it wouldn't work.
Does anyone know why and what the solution would be?
Thank you
These lines of your execFilter() method,
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
is only comparing the index 0 which is the numeric value not other columns.
Unless you compare the values with all the columns (all the indexes of rows[i].children) it won't give you the result you want.
So, you might wan't to run a for loop to iterate through all the children of rows[i].children and compare their text.
var foundResult = false;
for ( var counter = 0; counter < rows[i].children.length; counter++ )
{
if (show.indexOf(rows[i].children[0].textContent) != -1)
{
foundResult= true;
break;
}
}
if ( !foundResult )
{
display = 'none';
}
You mean something like this
var flt = ["zero","one","two","three"];
...
var showIt = show.indexOf(rows[i].children[0].textContent) !=-1;
for (var j=0;j<show.length;j++) {
if (flt[show[j]] == rows[i].children[1].textContent) {
showIt=true;
break;
}
}
rows[i].style.display = showIt?"":"none";
I have a table. I'd like to compare participants. If participant have several result points in the table, the script has to return sum of all participant's results. And so on for every participant.
The table is generated from database (".$row["pnt"]."".$row["station"]."".$row["res"]."):
Participant Station Points
aa Some1 1
dd Some1 2
aa sm2 3
dd sm2 4
bb sm3 5
ee sm3 6
For example I've to recieve such a new table:
aa - 4,
dd - 6,
bb - 5,
ee - 6
I've tried to do so:
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
jo.push(pnt1, pntR1, pntR2);
break;
}
}
}
console.log(jo);
});
});
But I understood that I'm on a wrong way. Please, help me. I really appreicate if some one could help me on this issue.
Updated after comments:
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr><td class="pnt">aa</td><td class="station">AES</td><td class="res">1</td></tr><tr><td class="pnt">dd</td><td class="station">AES</td><td class="res">2</td></tr>
<tr><td class="pnt">aa</td><td class="station">Science</td><td class="res">3</td></tr>
<tr><td class="pnt">dd</td><td class="station">Science</td><td class="res">4</td></tr><tr><td class="pnt">bb</td><td class="station">Аэродром</td><td class="res">5</td></tr>
<tr><td class="pnt">ee</td><td class="station">aeroport</td><td class="res">6</td></tr></tbody>
</table>
First, I would consider breaking your solution into three functions - one to extract the data from the HTML (which is a questionable practice in itself), one to transform the data, and one to output the new table. This way, your code is much more maintainable.
function getData() {
var rows = $("tbody tr");
var data = [];
rows.each(function(idx, row){
var pnt = row.find('.pnt').html(),
station = row.find('.station').html()),
res = parseInt(row.find('.res').html());
data.push(pnt, station, res);
});
}
Then I would consider something like this for the second method
// Pass the output from getData() into processData()
function processData(data){
var groupedKeys = {};
var groupedData = data.map(function(datum){
var name = datum[0];
var value = datum[2];
groupedKeys[name] = (groupedKeys[name] || 0) + (value || 0);
});
var transformedData = [];
Object.keys(groupedKeys).forEach(function(key){
transformedData.push([key, groupedKeys[key]]);
});
return transformedData;
}
The last method of course would need to be implemented by yourself, there's a ton that could be improved here, but it could be a good start.
I used an associative array (which is just an object in JavaScript) shown below:
http://jsfiddle.net/a5k6w300/
Changes I made:
var jo = [];
changed to an object instead of an array
var jo = {};
I also added the if(isNaN(object[key]) inside the inner loop in order to make sure that these didn't show as NaN as I continued adding them together.
$(document).ready(function () {
$("body").click(function () {
var rows = $("tbody tr");
var jo = {};
console.log(rows);
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j <= rows.length; j++) {
var pnt1 = $(rows[i]).find(".pnt").html();
var stations1 = $(rows[i]).find(".station").html();
var pntR1 = $(rows[i]).find(".res").html();
if (pnt1 == $(rows[j]).find(".pnt").html()) {
pntR1 = parseInt(pntR1);
pntR2 = parseInt($(rows[j]).find(".res").html());
if(isNaN(jo[pnt1])){
jo[pnt1] = 0;
}
jo[pnt1] += pntR1;
break;
}
}
}
console.log(jo);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="pntsRes">
<thead>
<tr>
<th>Участники</th>
<th>Баллы</th>
</tr>
</thead>
<tbody>
<tr>
<td class="pnt">aa</td>
<td class="station">AES</td>
<td class="res">1</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">AES</td>
<td class="res">2</td>
</tr>
<tr>
<td class="pnt">aa</td>
<td class="station">Science</td>
<td class="res">3</td>
</tr>
<tr>
<td class="pnt">dd</td>
<td class="station">Science</td>
<td class="res">4</td>
</tr>
<tr>
<td class="pnt">bb</td>
<td class="station">Аэродром</td>
<td class="res">5</td>
</tr>
<tr>
<td class="pnt">ee</td>
<td class="station">aeroport</td>
<td class="res">6</td>
</tr>
</tbody>
</table>
I have a DataTable that stores names only. I want to have a button that will add all the names in the DataTable to an text input field.
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>chris</td>
</tr>
<tr>
<td>mike</td>
</tr>
</tbody>
</table>
<button id="add" >ADD</button>
<input type="text" id="text">
</div>
After click the "add" button, I want the names to appear in the text field separated by a comma.
And if possible, If the button is clicked again, remove the names?
I created the whole solution on codepen. This is the function used:
var clicks = 0;
function csv() {
var box = document.getElementsByName('text')[0];
if(clicks === 0){
var newcsv = "";
var tds = document.getElementsByTagName("TD");
for(var i = 0; i < tds.length; i++)
{
newcsv += tds[i].innerHTML;
if(i != tds.length-1) newcsv += ",";
}
box.value = newcsv;
clicks++;
}
else{
clicks = 0;
box.value = "";
}
}
This is bound to onclick event of a button.
Assign id to input
<input type=text id="textbox"/>
Just loop though table
var table = document.getElementById("mytab1");
var textbox=document.getElementById("textbox")
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(textbox.value=="")
{
textbox.value=row.cells[j].innerText;
}
else
{
textbox.value+= textbox.value+','+row.cells[j].innerText;
}
}
}
I've a GridView with three rows like this
<tr>
<th>SlNo</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
I've the following code to traverse through the rows
var GridViewRow=GridView.getElementsByTagName('tr')
Here the row length is 3.
I travese through the GridViewRow using for loop .Here how will i get the tag name of the current element ie (th or td).
If the tagname is "TH" it should return and if it is "TD" it should take the value of TD.
How about this
var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
you can also try out
var tbl = document.getElementById('yourTableId');
var rows = tbl.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++)
{
if(rows[i].getElementsByTagName('td').length > 0)
{
//code to execute
}
else
{
continue;
}
}
var GridViewRow = GridView.getElementsByTagName('tr');
$(GridViewRow).each(function() {
var $this = $(this), td = $this.find('td');
if (td.length === 1) {
console.log(td.text());
}
});
this works for <tr> in which you have exactly one <td> if you use jquery, otherwise in plain javascript try this:
var GridViewRow = GridView.getElementsByTagName('tr'),
len = GridViewRow.length,
td;
while (--len) {
td = GridViewRow[len].getElementsByTagName('td');
if (td.length === 1) {
console.log(td[0].innerHTML);
}
}
});
You can check the tag name with jQuery :
$(this).attr("tag");
Later edit:
For raw javascript, use tagName:
element.tagName