How to find the id with the greatest value - javascript

I'm developing an ASP.NET MVC web page using Razor. Versions are Microsoft.AspNet.Mvc 5.2.3, Microsoft.AspNet.Razor 3.2.3, .NET Framework 4.7, C# and Javascript.
A view will have a table with these rows:
<tr id="level01_01"> ... </tr>
<tr id="level01_02"> ... </tr>
<tr id="level01_03"> ... </tr>
I need to know with jQuery which is the id for the latest row. In the above example is level01_03.
I create these rows with C# so I can add the input hidden with the latest id as value.
If I want to find it without an input hidden, I don't know how to do it. In this SO answer I've found how to get an id with a value greater than other, but this is not what I'm looking for:
<div id="div22" class="fade">text</div>
<div id="div35" class="fade">text</div>
<div id="div40" class="fade">text</div>
then jQuery
var divs = $('.fade').map(function(){
if (this.id.replace('div','') > 35) return '#'+this.id;
}).get().join(',');
$(divs).fadeTo("slow", 0.6);
BUT THIS IS NOT WHAT I'M LOOKING FOR.
I'm looking to get the id with the greatest number. In this example the id is level01_03.
How can I get the id with the greatest id?

You can use this to return the highest id value.
var ids = $("tr[id^='level01_']").map(function() {
return parseInt(this.id.replace("level01_", ""), 10);
}).get();
var highest = Math.max.apply(Math, ids);
console.log(highest)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="level01_01"> ... </tr>
<tr id="level01_02"> ... </tr>
<tr id="level01_03"> ... </tr>
</table>

There's several possible ways of doing this.
Firstly, assuming that the highest id will be the last one, you can just get the tr:last and read it's id:
var lastId = $('table tr:last').prop('id').spit('_')[1];
Alternatively, if the values are incremental you can just count the total number of tr elements:
var lastId = $('table tr').length;
Finally, if they are not in order you can use map() to build an array of the values, then Math.max to get the highest:
var highestId = Math.max.apply(Math, $('table tr').map(function() {
return parseInt(this.id.split('_')[1], 10);
}).get());
console.log(highestId);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="level01_10"></tr>
<tr id="level01_221"></tr>
<tr id="level01_3"></tr>
</table>

This function will set $el to the row with the highest valued Id.
var $el, max = 0;
$("tr").each(function() {
var i = parseInt(this.id.replace(/.*_(\d+)$/, "$1"));
if (i > max) {
max = i;
$el = $(this);
}
});

Use jQuery.filter
var divs = $('.fade').filter(function() {
return (+this.id.replace('div', '') > 35);
});
$(divs).fadeTo("slow", 0.6);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="div22" class="fade">text</div>
<div id="div35" class="fade">text</div>
<div id="div40" class="fade">text</div>
To get filtered IDs:
var divs = $('.fade').filter(function() {
return (+this.id.replace('div', '') > 35);
}).map(function() {
return this.id;
});
console.log(divs.get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="div22" class="fade">text</div>
<div id="div35" class="fade">text</div>
<div id="div40" class="fade">text</div>

if your TR having ascending ID than you can simply get last TR id like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
alert($("#tbl tr:last").attr("id"));
});
</script>
</head>
<body>
<table class="data" id="tbl">
<tr id="level01_01">
<th>Entry Header 1</th>
<th>Entry Header 2</th>
<th>Entry Header 3</th>
<th>Entry Header 4</th>
</tr>
<tr id="level01_02">
<td>Entry First Line 1</td>
<td>Entry First Line 2</td>
<td>Entry First Line 3</td>
<td>Entry First Line 4</td>
</tr>
<tr id="level01_03">
<td>Entry Line 1</td>
<td>Entry Line 2</td>
<td>Entry Line 3</td>
<td>Entry Line 4</td>
</tr>
<tr id="level01_04">
<td>Entry Last Line 1</td>
<td>Entry Last Line 2</td>
<td>Entry Last Line 3</td>
<td>Entry Last Line 4</td>
</tr>
</table>
</body>
</html>

You can achieve by comparing id as string like this code below:
var max = '';
$("#test tr").each(function() {
if (this.id.localeCompare(max) > 0) {
max = this.id;
}
});
console.log(max)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="test">
<tr id="level01_01"> ... </tr>
<tr id="level01_02"> ... </tr>
<tr id="level01_153"> ... </tr>
<div id="res"></div>
</table>

Related

HTML: change background row base on value

I've a table in HTML page and I want to color all the row in red when its first column gets a particular value.
I read something about that on StackOverflow and I added these two attributes (border-collapse and border-spacing) to my table
<table id="my-table" style="border-collapse:collapse; border-spacing:0 1px">
Now, in my JavaScript function, how can I set the background color in base of new value?
I tryied with theese:
if (value == 'broken') {my-table[i].css('background-color','red');} // OR
if (value == 'broken') {my-table[i].cells.style.background = 'red';}
where i is the index of the row I'm considering for. Nothing changes! Anyone can give me an advice? Thank you.
The following sample demonstrates a walk through an table...
you can adapt this to your sample...
You can also use the table Object...
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table key´s</title>
<style>
td{width:10px;height:10px;background:#ddd;}
tr:nth-child(5) td:nth-child(5){background:#f00;}
</style>
</head>
<body>
<div id="tableContainer">
</div>
<script>
var row=col=5,max=10;
tableContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
window.addEventListener("keyup", function(e){
var colDiff, rowDiff;
var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
if (keyMap.has(e.keyCode)){
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
[colDiff,rowDiff]=keyMap.get(e.keyCode);
row+=rowDiff;
col+=colDiff;
row = (row>max) ? max : (row < 1) ? 1 : row;
col = (col>max) ? max : (col < 1) ? 1 : col;
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
}
})
</script>
</body>
</html>
use document.getElementById and use a variable, it'll make life easier
e.g.
var bgtable = document.getElementById("my-table").getElementsByTagName("tr");
bgtable[i].style.backgroundColor = "red";
Also check your console for any errors and check that i 1) is being filled and 2) has the correct value.
In order to style a particular row's background color you need to set the css on the tr element. Without more context on where value is defined I can't really give you a specific code example.
Here is an example where I decide if a row is "broken" based on a data attribute set on the tr:
$("tbody tr", $("#my-table")).each(function() {
var tr = $(this);
if (tr.data("broken") == true) {
tr.css({
"background-color": "red"
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table" style="border-collapse:collapse; border-spacing:0 1px">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr data-broken="true">
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</tbody>
</table>

Hide rows in table B which already appear in table A

Using this code :
var table1 = $('#TableA').find('td:eq(1)').text();
var table2 = $("#TableB tr:gt(0)");
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
})
My Html Page Structure
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table id="TableA">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
</table>
<table id="TableB">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
<tr>
<td>Keyboard</td>
<td>150</td>
<td>7</td>
<td>#31234</td>
</tr>
</table>
</body>
</html>
"The second table in the images is the Table B"
My Table B changes from this :
Before
To this : After
Now my problem is, only one row is hidden. The row, where "speaker" is, is still displayed. I know that I must use a loop for this, but I don't where to implement the loop and how. I'm a newbie programmer and I know that I need more practice. Please Help Thank you in advance
<script type="text/javascript">
$('body').click(function(e){
var table1_tr = $('#TableA').find('tr'); <!--get the rows of first table-->
var table2 = $("#TableB tr:gt(0)");
table1_tr.each(function(i,e){ <!-- loop through rows of first table -->
var table1 = $(e).find('td:eq(1)').text();
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
});
})
});
</script>
you are checking the text of price in the first row of first table with td text of all the rows of second table
I modified script to loop through rows of first table and check them with all rows of second table
Hope this helps

Is it possible to find number of td's within table and then apply col width inside table tag by using Javascript?

Is it possible to add "col width" tag according to number of td tags, within Table tag. if there are 2 td's,then it should add 2 "col width". & if there are 3 then, 3 "col width". and so on.
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
Please can anyone help me,to add "col group" tag according to number of td.
Expected Output:-
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="20%"></col>
<col width="30%"></col>
</colgroup>
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="50%"></col>
</colgroup>
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
you need to first loop through the tables and get the td count for each table. and then create a colgroup based on the count of td's
something like this
var output = '';
$('table').each(function() {
var colCount = 0;
$(this).find('tr:nth-child(1) td').each(function() { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
console.log($(this));
});
var colgroupList = '';
for (i = 0; i < colCount; i++) { // Add a <colgroup></colgroup> for each <td>
colgroupList += '<col width="50%"></col>';
console.log(colgroupList);
}
console.log('<colgroup>' + colgroupList + '</colgroup>');
$(this).find("tbody").prepend('<colgroup>' + colgroupList + '</colgroup>');
output += $(this).html();
});
here's a working JSFIDDLE for the same.
In jQuery you can count the number of tds in the table by:
var count = $('#tableId td').length();
You can add atrributes to a table by doing:
$('#tableId').attr('name', 'value');
jQuery('table').each(function(){
var t = jQuery(this);
var count = t.children('tr').eq(0).find('td').length;
var colgroup = jQuery('<colgroup/>', { 'span': count });
for(var i = 1; i <= count; i++){
colgroup.append('<col/>',{ 'width' : (100/count)+'%' };
}
t.prepend(colgroup);
});
Untested but should be a good starting point
Yes, you can use jQuery to make things easy.
Here is an example (I used the id "table1" in the table):
$(document).ready(function () {
var size = $("#table1 tr:first > td").length;
var tg = '<colgroup span="' + size + '">';
for(x=0; x<size; x++) {
tg += '<col></col>';
}
tg += '</colgroup>';
$(tg).insertBefore('#table1 > tbody > tr:first');
});
Hope it helps.

Converting array that holding html elements into NodeList with Jquery

Html
<html>
<body>
<table>
<tr>
<td class="some"></td>
<td></td>
</tr>
<tr>
<td class="some"></td>
<td></td>
</tr>
<tr>
<td class="some"></td>
<td></td>
</tr>
</table>
</body>
</html>
Script
<script>
//Convert the table to columns
var columns = [];
var trs = $("table tr");
for(i=0;i<trs.length;i++){
var column = [];
for(j=0;j<2;j++){
column.push($(trs[j]).find("td")[i]);
}
columns.push(column);
}
</script>
The Problem
I can't use $.find method on the array to filter by selector.
For Example, this code won't find anything:
<script>
$(columns[0]).find(".some").length // will print 0
</script>
Question
How can I trick jQuery engine to assume that columns[0] is NodeList?
I don't want to use cloning because it's not good enough for my project.
Thanks.

How do you rearange text in elements using javascript and jquery

I am trying to select all the elements with class "name" and when I click on one radio button it flips the last and first name around, so: Hanks, Tom || Tom, Hanks. Here is what I have so far:
HTML:
<h1>Address Book</h1>
<p>Show Names as:</p>
<input name="lastfirst" value="last" type="radio">First, Last
<input name="firstfirst" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbody>
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks,</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis,</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey,</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise,</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks,</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis,</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey,</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise,</td>
</tr>
</tbody>
</table>
</div>
Here is my jquery. I used a filler of .hide() because other than selecting the elements I am not sure how to do this. Just some hints would help. I am not sure how to separate the first and last name. If I could figure out how to simply swap the first and last name into a variable I could definitely figure out the rest.
$(document).ready(function(){
$("input[name='lastfirst']").click(function(){
$(".name").hide();
});
$("input[name='firstfirst']").click(function(){
$(".name").hide();
});
});
DEMO
$(document).ready(function () {
$("input[name='change_last_first']:nth(0)").prop('checked', true)
$("input[name='change_last_first']").change(function () {
$(".name").text(function (_, old_txt) {
var new_txt = old_txt.split(' ').reverse();
return new_txt.toString().replace(',,', ' ') + ',';
});
});
});
HTML changed
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
References
.text()
.change()
.replace()
.split()
.toString()
.reverse()
Split it first using.
var splStr = input.split(/[ ,]+/);
now concatinate using input=splStr[1]+splStr[0];
you can separate the text using split function input.split(/[ ,]+/); along with a regular expression to separate each "word" within the input.
you could then assign each value to a new variable
ex:
var a = array[0], b = array[1]
From there you could concatenate the array values into any order you choose.

Categories