I have an HTML data table, I attached code and also attached test case. Here I do dynamically prepend the row in data table,that means I want to add a row in first position with serial number dynamically. Test Case Datatable
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/colreorder/1.5.2/css/colReorder.dataTables.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/colreorder/1.5.2/js/dataTables.colReorder.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.colVis.min.js"></script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Age</th>
<th>Salary.</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger Nixon</td>
<td>61</td>
<td>$320,800</td>
</tr>
<tr>
<td>2</td>
<td>Garrett Winters</td>
<td>63</td>
<td>$170,750</td>
</tr>
</tbody>
</table>
<input type="button" value="addNew Row" onclick="addNewRow()"/>
</body>
</html>
And the JavaScript is:
function addNewRow() {
var table = $('#example').dataTable();
var rowLen = table.fnGetData().length;
var srNo = rowLen + 1;
var t = $('#example').DataTable();
t.row.add(['1','vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
t.draw(false);
$('#lclSsrContainer_' + rowLen).attr('style', 'color: #0822f3;');
}
How to add dynamically in first position with dynamic serial number, and no change in data table?
Datatable has no property liked
prepend()
If we want to add a row in first postion it collapse our datatable functionalities,So finally after adding a row
t.row.add([rowLen,'vuyv','54','89855']).node().id = 'demo_' + rowLen;
just reorder the table as like
$('.sorting_asc').click();
this jquery function can solve my problem.It comes first position
because your table is set to sort on "s.no" the row will be inserted based in this value so if you did :
t.row.add(['0','vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
that would be placed in the first row because the "s.no" value is "0" and if you wanted it at the end row every time:
t.row.add([rowLen,'vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
the problem is though is if you waned "s.no" as any value and still be the first row you would have to remove the sort from the table
hope this helps
Related
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>
Trying to sort the table by just duplicating the row and not the entire table. On click of the column header that column's data must be compared and sorted and the rows rearranged , but I don't know where i am going wrong.Here is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table Sort</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$('th').click(function() {
var ColNo = parseInt($(this).index());
var rows= $('tbody').children('tr');
var TotRows = parseInt(rows.length);
for (var i = TotRows-1; i >= 0; i--) {
for (var j = TotRows-1; j > 0; j--) {
var jint = parseInt(j);
var frstval = parseInt(rows[jint].getElementsByTagName("td")[ColNo].innerHTML);
var scndval = parseInt(rows[jint - 1].getElementsByTagName("td")[ColNo].innerHTML);
if (frstval < scndval) {
var a = frstval < scndval;
alert(a);
var sourceRow = $('tr').eq(jint);
alert(sourceRow);
var targetRow = $('tr').eq(jint-1);
targetRow.after(sourceRow.clone());
sourceRow.replaceWith(targetRow);
}
}
}
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>AAA</td>
<td>28</td>
</tr>
<tr>
<td>22</td>
<td>BBB</td>
<td>29</td>
</tr>
<tr>
<td>33</td>
<td>CCC</td>
<td>21</td>
</tr>
<tr>
<td>44</td>
<td>DDD</td>
<td>24</td>
</tr>
</tbody>
</table>
</body>
</html>
Better if you use a dhtmlXgrid... It's easier to implement, and you can create a JSON object of the entire dataset that you want to fill in the table. Then, just parse the JSON object into the dhtmlXgrid. With dhtmlXgrid, sorting, column size, column drag and drop, row drag and drop, etc., all such activities can be made automatically.
General info: I am trying to make a table using the JQuery mobile. Up to this point my table looks good however, I have some minor issues.
Here is the code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<style>
th
{
border-bottom: 1px solid #d6d6d6;
}
tr:nth-child(even)
{
background:#e9e9e9;
}
</style>
</head>
<body>
<h1>My Name</h1>
<div data-role="page" id="pageone">
<div data-role="header">
<h1> Cs496 Hw2</h1>
<h2> By: My Name here</h2>
</div>
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="columntoggle" class="ui-responsive ui-shadow" id="myTable">
<thead>
<tr>
<th data-priority="1">No.</th>
<th>School Name</th>
<th data-priority="2">LOGO</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="schoolName_0">schools[0].name</td>
<td id="schoolImage_0">schools[0].image</td>
</tr>
<tr>
<td>2</td>
<td id="schoolName_1">schools[1].name</td>
<td id="schoolImage_1">schools[1].image</td>
</tr>
<tr>
<td>3</td>
<td id="schoolName_2">schools[2].name</td>
<td id="schoolImage_2">schools[2].image</td>
</tr>
<tr>
<td>4</td>
<td id="schoolName_3">schools[3].name</td>
<td id="schoolImage_3">schools[3].image</td>
</tr>
<tr>
<td>5</td>
<td id="schoolName_4">schools[4].name</td>
<td id="schoolImage_4">schools[4].image</td>
</tr>
<tr>
<td>6</td>
<td id="schoolName_5">schools[5].name</td>
<td id="schoolImage_5">schools[5].image</td>
</tr>
<tr>
<td>7</td>
<td id="schoolName_6">schools[6].name</td>
<td id="schoolImage_6">schools[6].image</td>
</tr>
</tbody>
</table>
<script type='text/javascript'>
function school(name,image){
this.name = name;
this.image = image;
}
var schools = [
new school('Oregon State University', "http://www.sports-logos-screensavers.com/user/OregonStateBeavers.jpg"),
new school('University of Oregon', "http://www.sports-logos-screensavers.com/user/Oregon_Ducks06.jpg"),
new school('Stanford University', "http://www.sports-logos-screensavers.com/user/Stanford_Cardinal.jpg")
new school('University of Southern California', "http://www.sports-logos-screensavers.com/user/USC_Trojans2.jpg"),
new school('University of Washington', "http://www.sports-logos-screensavers.com/user/Washington_Huskies2.jpg"),
new school('San Diego State University', "http://www.sports-logos-screensavers.com/user/SanDiegoStateAztecs3.jpg"),
new school('Florida State University', "http://www.sports-logos-screensavers.com/user/FloridaStateSeminoles.jpg")
];
</script>
</div>
</body>
</html>
Q: What I want to do is use Jquery to insert the contents of the schools array into the correct columns and rows. I wanted to do this by making an array of objects and then insert the associated element in the correct location in the table (where logos are links to images).
I have tried using both Jquery's append and appendto commands in the script portion of my html but that did not work. Also I tried using the document.getElementbyId(...) but that did'nt work either. I believe the script portion of my html is never being called.
Any Ideas are welcome.
The reference to schools[x].name and schools[x].image is not how javascript, or jQuery for that matter, will execute those. Infact this is probably rendering as straight text in your html <td> tags rather than the array element value you are hoping for.
Here is what I would do.
First, add an appropriate class to each of the <td> elements, and a rel attr to hold the counter like so:
<tr>
<td>1</td>
<td class='name' rel='0'></td>
<td class='image' rel='0'></td>
</tr>
Then, iterate over each of the <td> elements in the table, using the rel tag as the array index to retrieve the values from; finally, apply the values to the <td> tags with the .html('...') function, like so:
$.each( $("table#myTable tr td"), function(i,e){
var $this = $(this), //set $(this) object to a variable rather than referencing it multiple times
rel = parseInt( $this.attr('rel') );
//only look for td elements that have a class
if( $this.hasClass('name') )
$this.html( schools[ rel ].name );
if( $this.hasClass('image') )
$this.html( '<img src="' + schools[ rel ].image + '"/>' );
});
I haven't tested this, but I think the logic is sound...
I want to populate a predefined html table using JavaScript:
<table>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<div id='data'/>
</table>
using
document.getElementById('data').innerHTML = ....
But since <div> is not allowed inside of <table> above code doesn't work. What is the correct way to achieve this?
Instead of Div you can use tr and td.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("tbody").item(0);
row=document.createElement("tr");
cell1 = document.createElement("td");
cell2 = document.createElement("td");
textnode1=document.createTextNode(content);
textnode2=document.createTextNode(morecontent);
cell1.appendChild(textnode1);
cell2.appendChild(textnode2);
row.appendChild(cell1);
row.appendChild(cell2);
tabBody.appendChild(row);
}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>
In the most basic sense:
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td colspan="2">
<div> LOTS O' CONTENT </div>
</td>
</tr>
</table>
You've answered yourself - put the div in the right location - either inside the table or outside. The javascript will work, whether the div will be displayed where you'd like it to, is a different question :)
Note: this is meant to be a community wiki post
The following code using simple dom methods fails to add rows to the table. What's the issue?
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytable = document.getElementById('mytable');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytable.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tr>
<td>This is a row</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
The issue at hand here is that the <table> element's correct structure is not present. When dealing with tables, the basic structure is:
<table>
<thead>
<tr>
<th>Heading for the table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A row of data</td>
</tr>
</tbody>
</table>
The logic is that when dealing with tables, you want to keep the labels of the columns, and the actual data separate. Because most browsers fill in the <tbody> as part of the process of fixing broken HTML, few people realize this. When the browser sees you adding a <tr>, it doesn't know if you're trying to add it to the <thead> or the <tbody>, so it fails.
The following shows the correct method for adding the rows:
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytbody.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>This is a row</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Any additional row needs to be added then take the first child of tableID and then use appendChild() method:
var tbl=document.getElementById("tbl");
var row=document.createElement("tr");
var cel=document.createElement("td");
cel.innerHTML='sometext';
row.appendChild(cel);
tbl.children[0].appendChild(row);