pure javascript table row pagination - javascript

I try to do pagination table but I want to reference table row to show 3 data per page
How Could i do
Fiddle: http://jsfiddle.net/578hmpv2/
This Code
var current_page = 1;
var records_per_page = 3;
var l = document.getElementById("listingTable").rows.length
function prevPage()
{
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage()
{
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page)
{
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("listingTable");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
for (var i = (page-1) * records_per_page; i < (page * records_per_page) && i < l; i++) {
listing_table.rows[i].style.display = ""
}
page_span.innerHTML = page + "/" + numPages();
if (page == 1) {
btn_prev.style.visibility = "hidden";
} else {
btn_prev.style.visibility = "visible";
}
if (page == numPages()) {
btn_next.style.visibility = "hidden";
} else {
btn_next.style.visibility = "visible";
}
}
function numPages()
{
return Math.ceil(l / records_per_page);
}
window.onload = function() {
changePage(1);
};
How can I change it to make it perfect? Sorry for my bad English, can't explain all what I need, hope you understand what I need!
Thanks !

I think this does what you want. I've tried to keep the code more or less structured how you wrote it, but I've changed a few things:
I've used onclick rather than a javascript scheme href because the stack overflow code editor didn't run the href.
I've used current_page rather than a hard-coded 1 in the onload function.
Other than that I think the comments explain the situation.
Note that I've had to add one to the loop and subtracted one when doing the page count to allow for the header row.
var current_page = 1;
var records_per_page = 3;
var l = document.getElementById("listingTable").rows.length
function prevPage()
{
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage()
{
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page)
{
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("listingTable");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
[...listing_table.getElementsByTagName('tr')].forEach((tr)=>{
tr.style.display='none'; // reset all to not display
});
listing_table.rows[0].style.display = ""; // display the title row
for (var i = (page-1) * records_per_page + 1; i < (page * records_per_page) + 1; i++) {
if (listing_table.rows[i]) {
listing_table.rows[i].style.display = ""
} else {
continue;
}
}
page_span.innerHTML = page + "/" + numPages();
if (page == 1) {
btn_prev.style.visibility = "hidden";
} else {
btn_prev.style.visibility = "visible";
}
if (page == numPages()) {
btn_next.style.visibility = "hidden";
} else {
btn_next.style.visibility = "visible";
}
}
function numPages()
{
return Math.ceil((l - 1) / records_per_page);
}
window.onload = function() {
changePage(current_page);
};
<table id="listingTable">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>Example</td>
<td>Page 3</td>
<td>UK</td>
</tr>
</table>
<a onclick="prevPage()" href='#' id="btn_prev">Prev</a>
<a onclick="nextPage()" href='#' id="btn_next">Next</a>
page: <span id="page"></span>

for (var i = 0; i < l; i++) {
listing_table.rows[i].style.display = "none"
}
add this in your changePage function
jsfiddle

Related

How to add Previous and Next in Pagination

This is my pagination
pagination.js
$(document).ready(function() {
var totalRows = $('#myTable').find('tbody tr:has(td)').length;
var recordPerPage = 10;
var totalPages = Math.ceil(totalRows / recordPerPage);
var $pages = $('<div id="pages"></div>');
for (i = 0; i < totalPages; i++) {
$('<span class="pageNumber"> ' + (i + 1) + '</span>').appendTo($pages);
}
$pages.appendTo('#myTable');
$('.pageNumber').hover(
function() {
$(this).addClass('focus');
},
function() {
$(this).removeClass('focus');
}
);
$('table').find('tbody tr:has(td)').hide();
var tr = $('table tbody tr:has(td)');
for (var i = 0; i <= recordPerPage - 1; i++) {
$(tr[i]).show();
}
$('span').click(function(event) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).text() - 1) * recordPerPage;
var nEnd = $(this).text() * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
});
});
Table.php
<table id="myTable" class="table table-bordered " width="100%" cellspacing="0">
</table>
Hello Guys, Can anyone help with this problem. I'm doing pagination in may patient table but my pagination is in my picture above. I want my pagination to start to "Previous 1 2 3 Next" but in my pagination is only " 1 2 3". I want to add Previous and Next. Sorry Guys, I'm just a beginner.
In my example I'm using a table with just 10 entries and recordPerPage is set to 2 for convenience. If there is no previous or next page, previous and next simply don't work. It could be adjusted to not show previous or next instead but maybe this isn't necessary and you're already content with this solution.
$(document).ready(function() {
var totalRows = $('#myTable').find('tbody tr:has(td)').length;
var recordPerPage = 2;
var totalPages = Math.ceil(totalRows / recordPerPage);
var $pages = $('<div id="pages"></div>');
for (i = 0; i < totalPages; i++) {
$('<span class="pageNumber"> ' + (i + 1) + '</span>').appendTo($pages);
}
var next = $('<span class="next" data-target="2">Next</span>');
next.appendTo($pages);
var prev = $('<span class="prev" data-target="0">Previous</span>');
prev.prependTo($pages);
$pages.appendTo('#myTable');
$('.pageNumber').hover(
function() {
$(this).addClass('focus');
},
function() {
$(this).removeClass('focus');
}
);
$('table').find('tbody tr:has(td)').hide();
var tr = $('table tbody tr:has(td)');
for (var i = 0; i <= recordPerPage - 1; i++) {
$(tr[i]).show();
}
$('span.pageNumber').click(function(event) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).text() - 1) * recordPerPage;
var nEnd = $(this).text() * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(".next").data("target", parseInt($(this).text()) + 1);
$(".prev").data("target", parseInt($(this).text()) - 1);
});
$('span.next').click(function(event) {
if ($(this).data("target") <= $(".pageNumber:last").text()) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).data("target") - 1) * recordPerPage;
var nEnd = $(this).data("target") * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(this).data("target", $(this).data("target") + 1);
$(".prev").data("target", $(".prev").data("target") + 1);
}
});
$('span.prev').click(function(event) {
if ($(this).data("target") >= $(".pageNumber:first").text()) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).data("target") - 1) * recordPerPage;
var nEnd = $(this).data("target") * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(this).data("target", $(this).data("target") - 1);
$(".next").data("target", $(".next").data("target") - 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
<tr>
<td>7</td>
</tr>
<tr>
<td>8</td>
</tr>
<tr>
<td>9</td>
</tr>
<tr>
<td>10</td>
</tr>
</table>
This may not answer your question directly but as your question says you are a beginner with JavaScript. As a beginner I'd always try to use existing plugins / librarys which solve my problems before I attempt solving them by myself.
The easiest solution for your problem would be to use something like Datatables. It offers great support for customizing and also comes with your desired pagination out-of-the-box.
If you need help converting your code to datatables ask a new question.

Sorting Table data onclick <th>in Google-App script

I am trying to sort the data(asc or desc) in the table. For this one I want to sort the Date of VL & Date/Time of Application whenever I click on each header. However, my current code is not doing anything everytime I click it. But when I tried it on a static data it's working.
Here's my code below:
<? var data = SpreadsheetApp
.openById('sheet ID')
.getSheetByName("VL Request")
.getDataRange()
.getValues();
var timeStamp = [0];
var rid = [1];
var ldap = [2];
var aname = [7];
var lob = [9];
var dovl = [5];
var rol = [6];
var tlapprov = [12];
var tlrem = [14];
var stat = [13];
var schedrem = [11];
var tl = [3];
var pocldap = [15];
var omldap = [16];
var userName = Session.getEffectiveUser().getUsername();
?>
<table id="vllist" class="vllist2">
<tr>
<th colspan=11>POC VIEW</th>
</tr>
<tr>
<th colspan=11>Application for Date Range: <?= [formattedStart] ?> - <?= [formattedEnd] ?></th>
</tr>
<tr>
<th style="display:none;">Request ID</th>
<th>LDAP</th>
<th>Agent Name</th>
<th>Lane</th>
<th onclick="sortTable(4)">Date of VL</th>
<th>Reason of Leave</th>
<th>POC Approval</th>
<th>POC Remarks</th>
<th>Scheduler's Approval</th>
<th>Scheduler's Remarks</th>
<th onclick="sortTable(10)">Date/Time of Application</th>
</tr>
<? for (var i = 1; i < data.length; i++) { ?>
<tr>
<? if ((data[i][tlapprov] === "Pending") && ((data[i][pocldap] === userName) || (data[i][omldap] === userName)) && (data[i][dovl] >= startDate) && (data[i][dovl] <= endDate)) { ?>
<?
var vldate = data[i][dovl];
var formattedDateVL = (vldate.getMonth()+1) + '/' + vldate.getDate() + '/' + vldate.getYear();
?>
<td class="hide">
<?= data[i][rid] ?>
</td>
<td>
<?= data[i][ldap] ?>
</td>
<td>
<?= data[i][aname] ?>
</td>
<td>
<?= data[i][lob] ?>
</td>
<td>
<?= [formattedDateVL] ?>
</td>
<td>
<?= data[i][rol] ?>
</td>
<td>
<?= data[i][tlapprov] ?>
</td>
<td>
<?= data[i][tlrem] ?>
</td>
<td>
<?= data[i][stat] ?>
</td>
<td>
<?= data[i][schedrem] ?>
</td>
<td class="lefttext">
<?= data[i][timeStamp] ?>
</td>
<? } ?>
</tr>
<? } ?>
</table>
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("vllist");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
</script>
What I would do is call the DATA into the table as normal... Then use JS to sort the records in the HTML table.
I think what you were trying to do is sort the data alphabetically first then display the data into the table . So rather put the data as is into the table, then use a sort Table function ..
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchcount ++;
} else {
/*If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again.*/
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {
cursor: pointer;
}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
<p><strong>Click the headers to sort the table.</strong></p>
<p>The first time you click, the sorting direction is ascending (A to Z).</p>
<p>Click again, and the sorting direction will be descending (Z to A):</p>
<table id="myTable">
<tr>
<!--When a header is clicked, run the sortTable function, with a parameter, 0 for sorting by names, 1 for sorting by country:-->
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Country</th>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
</table>
Here's a simple solution for being able to sort in a spreadsheet by clicking on check boxes above the the header row.
function onEdit(e) {
var sh=e.range.getSheet();
if(sh.getName()=='Sheet1') {
if(e.range.rowStart==1 && e.range.columnStart<=sh.getLastColumn()) {
sh.getRange(3,1,sh.getLastRow()-1,sh.getLastColumn()).sort({column:e.range.columnStart,asc:(e.value=="TRUE")?true:false});
}
}
}
Here's what the Spreadsheet Might look like:
According to the Best Practices for UI with Apps Script, you should load your data asynchronously.
To show you how to do this + to create a proper sorting function for you, I have created the following sample Sheet:
Code.gs
function createSidebarWithHTML() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
function getInitialData() {
var result = SpreadsheetApp.getActiveSpreadsheet().getDataRange().getValues();
result.shift(); //Removes header row from results
//Returns an array of arrays [rows, rows, ...] where rows = [column, column, column, ...]
return result;
}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table id='mytable'>
<thead>
<tr>
<th colspan=4>POC VIEW</th>
</tr>
<tr>
<th colspan=4>Sample data!</th>
</tr>
<tr>
<th onclick=sort(0)>Header 1</th>
<th onclick=sort(1)>Header 2</th>
<th onclick=sort(2)>Header 3</th>
<th onclick=sort(3)>Header 4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var loadedData = null;
function loadTable(data) {
loadedData = data; //For caching of the received data.
var tablebody = document.querySelector('#mytable > tbody');
for (var i=0; i<data.length; i++) {
var newRow = document.createElement("tr");
for (var j=0; j<data[i].length; j++) {
var newCell = document.createElement("td");
var cellContent = document.createTextNode(data[i][j]);
newCell.appendChild(cellContent);
newRow.appendChild(newCell);
}
tablebody.appendChild(newRow);
}
}
function sort(row) {
var sortedData = loadedData;
//Sort data based on row Number
sortedData.sort(function(a,b) {
return a[row]-b[row];
});
var tablebody = document.querySelector('#mytable > tbody');
tablebody.innerHTML = ''; //Clear table body
for (var i=0; i<sortedData.length; i++) {
var newRow = document.createElement("tr");
for (var j=0; j<sortedData[i].length; j++) {
var newCell = document.createElement("td");
var cellContent = document.createTextNode(sortedData[i][j]);
newCell.appendChild(cellContent);
newRow.appendChild(newCell);
}
tablebody.appendChild(newRow);
}
}
//initialize data
function initialize() {
google.script.run.withSuccessHandler(loadTable).getInitialData();
}
initialize();
</script>
</body>
</html>

move the row/s up when data matched with the inputted string

I need to move the row/s that is matched with the inputted string.
on the code below you need to click first the row before you can move that particular row to the top.
Instead of clicking the row, I just wanted to input a string or char then onclick, if there's a match on the html table, the row that matched or like on the string inputted will be moved on the top of the table grid.
var index;
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if (direction === "up") {
if (index < rows.length) {
parent.insertBefore(rows[index], rows[index - index + 1]);
index--;
}
}
}
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
</table>
<input type="text" id="txt">
<button onclick="upNdown('up');">&ShortUpArrow;</button>
what I need to do is upon click of the button, find the matching data and move the row to the top.
If I correctly understand you problem, Think this is your answer. This code find the first match of input and move that to first row. If the input be empty, it will do nothing.
var index = 0;
function findMatchRow(rows, str) {
if (!str.length) {
return null;
}
for (var i = 1; i < rows.length; i++) {
for (var j = 0; j < rows[i].children.length; j++) {
if (rows[i].children[j].textContent.match(str)) {
return i;
}
}
}
return 0;
}
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index && index > -1 ? index : 0].parentNode,
inpt = document.getElementById("txt").value;
var matchedRow = findMatchRow(rows, inpt);
if (matchedRow) {
if (direction === "up") {
index = matchedRow;
parent.insertBefore(rows[index], rows[index - index + 1]);
index--;
if (index < 0) {
index = rows.length - 1;
}
}
}
}
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
</table>
<input type="text" id="txt">
<button onclick="upNdown('up');">&ShortUpArrow;</button>

To select a row from a web table?

Here is the code that I used to select a row from this particular table. The following code has to select the row containing Position-"Engineer' and Age=34. Instead it is selecting the entire table. Can someone explain me why is this happening and what can be added to avoid it.
$(document).ready(function(){
var dict={1:"Engineer",3:"34"};
var a=Object.keys(dict);
if ( (a+"").match(/^\d+$/) )
{
var colidx = Object.keys(dict);
$('#example tbody tr').filter(function(idx, ele) {
var val = colidx.filter(function(colname, idx) {
var colvalue = dict[colname];
return ($(ele).find('td').eq(colidx[idx]).text() == colvalue)
});
return val.length == colidx.length }).css('background-color', 'red');
}
else
{
var coli = {};
$('#example thead tr th').filter(function(i, e) {
var keycol = e.textContent;
var keyval = Object.keys(dict).indexOf(keycol);
if (keyval != -1) {
coli[keycol] = i;
}
});
var colidx = Object.keys(coli);
$('#example tbody tr').filter(function(idx, ele) {
var val = colidx.filter(function(colname, idx) {
var colvalue = dict[colname];
var colindex = coli[colname];
return ($(ele).find('td').eq(colindex).text() == colvalue)
});
return val.length == colidx.length;
}).css('background-color', 'red');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kavya</td>
<td>Engineer</td>
<td>Mumbai</td>
<td>34</td>
<td>2011/04/25</td>
<td>1,20,000</td>
</tr>
<tr>
<td>Archana</td>
<td>Accountant</td>
<td>Delhi</td>
<td>21</td>
<td>2011/07/25</td>
<td>170,750</td>
</tr>
<tr>
<td>kranthi</td>
<td>Technical Author</td>
<td>Chennai</td>
<td>23</td>
<td>2009/01/12</td>
<td>86,000</td>
</tr>
<tr>
<td>Srija</td>
<td>Javascript Developer</td>
<td>Pune</td>
<td>22</td>
<td>2012/03/29</td>
<td>433,060</td>
</tr>
<tr>
<td>Priyanka</td>
<td>Engineer</td>
<td>Mysore</td>
<td>33</td>
<td>2008/11/28</td>
<td>162,700</td>
</tr>
<tr>
<td>Himanshu</td>
<td>Integration Specialist</td>
<td>Goa</td>
<td>51</td>
<td>2012/12/02</td>
<td>372,000</td>
</tr>
<tr>
<td>Vishwam</td>
<td>System Architect</td>
<td>Jharkand</td>
<td>69</td>
<td>2011/04/25</td>
<td>320,800</td>
</tr>
<tr>
<td>Akhila</td>
<td>Sales Assistant</td>
<td>Hyderabad</td>
<td>59</td>
<td>2012/08/06</td>
<td>137,500</td>
</tr>
<tr>
<td>Ashwini</td>
<td>Javascript Developer</td>
<td>Bhuvaneshwar</td>
<td>39</td>
<td>2009/09/15</td>
<td>205,500</td>
</tr>
</tbody>
</table>
You could do something like this
UPDATE: Example using a dict with index-value and Name-value
$(function() {
var dict = {0:"Srija", "Office": "Pune", 3: "22"};
dict = buildIndexValueDictionary(dict);
runSearchByDict(dict);
});
function buildIndexValueDictionary(dict){
var header = $("table thead tr th")
var result = {};
for (var key in dict) {
if(isNaN(key)){
result[getIndexByColumnName(header, key)] = dict[key];
}
else{
result[key] = dict[key];
}
}
return result;
}
function getIndexByColumnName(header, key){
for(var i = 0; i < header.length; i++){
if($(header[i]).html() == key){
return i;
}
}
}
function runSearchByDict(dict) {
var arrayIndex = new Array();
var arrayValues = new Array();
for (var key in dict) {
arrayIndex.push(key);
arrayValues.push(dict[key]);
}
var matchedRows = selectRowByDict(arrayIndex, arrayValues);
for (var i = 0; i < matchedRows.length; i++) {
console.log($(matchedRows[i]).html());
}
}
function selectRowByDict(arrayIndex, arrayValues){
var result = new Array();
var rows = $("table tbody tr");
for(var j = 0; j < rows.length; j++){
var cells = $(rows[j]).find("td");
var validRow = true;
for(var i = 0; i < arrayIndex.length && validRow; i++){
if($(cells[arrayIndex[i]]).html() != arrayValues[i]){
validRow = false;
}
}
if(validRow){
result.push($(rows[j]));
}
}
return result;
}

Javascript-Using single function instead of multiple

Here the code:
<script type="text/javascript">
function ChangeColor1()
{
t1.style.backgroundColor = 'pink';
t2.style.backgroundColor = '';
t3.style.backgroundColor = '';
}
function ChangeColor2()
{
t1.style.backgroundColor = '';
t2.style.backgroundColor = 'pink';
t3.style.backgroundColor = '';
}
function ChangeColor3()
{
t1.style.backgroundColor = '';
t2.style.backgroundColor = '';
t3.style.backgroundColor = 'pink';
}
</script>
</head>
<body>
<table width="50%" border="1" >
<tr id="t1" onclick="ChangeColor1();">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr id="t2" onclick="ChangeColor2();">
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr id="t3" onclick="ChangeColor3();">
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
</body>
In this program there are 3 functions are used. I want to do this task using a single function instead of one.
function changeColor(n){
t1.style.backgroundColor = n == 1 ? 'pink' : '';
t2.style.backgroundColor = n == 2 ? 'pink' : '';
t3.style.backgroundColor = n == 3 ? 'pink' : '';
}
... onclick="changeColor(1)" ...
Would be how I'd refactor it. Or better yet make an array of var ts = [t1,t2,t3] then reference ts[n].
var ts = [t1,t2,t3];
function changeColor(n){
for (var i = 0; i < ts.length; i++){
ts[i].style.backgroundColor = (i+1) == n ? 'pink' : '';
}
}
Or you can reference the id directly:
function changeColor(n){
for (var i = 1; i < 4; i++){
document.getElementById('t'+i).style.backgroundColor = n == i ? 'pink' : '';
}
}
You can also take it a step farther and reference the row itself instead of specifying the index as an argument (keeping it generic):
function changeColor(t){
for (var n = 1; n < 4; n++){
var tn = document.getElementById('t'+n);
tn.style.backgroundColor = tn.id == t.id ? 'pink' : '';
}
}
... onclick="changeColor(this);" ...
DEMO
NOTE: Not all browsers will accept t1.style without the document.getElementById
function ChangeColor(row) {
var idx=row.id;
for (var i=1;i<=3;i++) {
document.getElementById("t"+i).style.backgroundColor = (idx==="t"+i)?"pink":"";
}
}
using
<tr id="t1" onclick="ChangeColor(this);">
<tr id="t2" onclick="ChangeColor(this);">
<tr id="t3" onclick="ChangeColor(this);">

Categories