Refreshing a table without refreshing page or stopping function - javascript

I'm working on a basic genetic algorithm that guesses the words you type into it. I have all of that working but for some reason, the guesses are not live updating, but rather only using the last iteration. Here's my current updateGuesses function:
function updateGuesses(){
var sortAtt = attempts.sort(cmpFitness);
bestAttempt = sortAtt[0];
GUESS.innerHTML= bestAttempt.sentence;
//Top Guesses from past generations
pastGuesses[5] = pastGuesses[4];
pastGuesses[4] = pastGuesses[3];
pastGuesses[3] = pastGuesses[2];
pastGuesses[2] = pastGuesses[1];
pastGuesses[1] = pastGuesses[0];
pastGuesses[0] = {sentence:bestAttempt.sentence, gen:generation};
document.getElementById("gen1").innerHTML = pastGuesses[0].gen;
document.getElementById("guess1").innerHTML = pastGuesses[0].sentence;
document.getElementById("gen2").innerHTML = pastGuesses[1].gen;
document.getElementById("guess2").innerHTML = pastGuesses[1].sentence;
document.getElementById("gen3").innerHTML = pastGuesses[2].gen;
document.getElementById("guess3").innerHTML = pastGuesses[2].sentence;
document.getElementById("gen4").innerHTML = pastGuesses[3].gen;
document.getElementById("guess4").innerHTML = pastGuesses[3].sentence;
document.getElementById("gen5").innerHTML = pastGuesses[4].gen;
document.getElementById("guess5").innerHTML = pastGuesses[4].sentence;
document.getElementById("gen6").innerHTML = pastGuesses[5].gen;
document.getElementById("guess6").innerHTML = pastGuesses[5].sentence;
}
This function is called in a while loop that updates the array every iteration. The end result that's displaying is correct but for some reason it's not updating each loop. Here's the table structure:
<table id="myTable">
<tr>
<td>Generation</td>
<td>Best Guess</td>
</tr>
<tr>
<td><span id="gen1">1</span></td>
<td id="guess1">N/A</td>
</tr>
<tr>
<td id="gen2">2</td>
<td id="guess2">N/A</td>
</tr>
<tr>
<td id="gen3">3</td>
<td id="guess3">N/A</td>
</tr>
<tr>
<td id="gen4">4</td>
<td id="guess4">N/A</td>
</tr>
<tr>
<td id="gen5">5</td>
<td id="guess5">N/A</td>
</tr>
<tr>
<td id="gen6">6</td>
<td id="guess6">N/A</td>
</tr>
</table>
EDIT: Here's my main method that includes the loops:
function main(){
var string;
var score;
generation = 0;
goal = document.getElementById("goalField").value;
string_length = goal.length
//Populate attempts with random strings
for (let i = 0; i < POPULATION; i++){
string = randomString();
score = stringScore(string);
attempts[i] = {sentence:string, sentenceScore:score};
}
//Retrieve Probabilities for each attempt
fitness()
//Find best Guess
updateGuesses()
while(bestAttempt.sentenceScore != string_length){
repopulate()
generation++;
sortAtt = attempts.sort(cmpFitness)
updateGuesses()
}
The while loop basically checks if the best sentence guessed is correct and if it isn't it creates a new array of guesses. The goal is to update the HTML table with the new guesses each time it runs through the while loops.

Thank you #RobbieD ! I figured it out by using setInterval with an if statement within it instead of a while loop.
var repeat = setInterval(doAgain,100);
}
function doAgain(){
//GUESS.innerHTML=attempts[0].fitness
if(bestAttempt.sentenceScore != string_length){
repopulate()
generation++;
sortAtt = attempts.sort(cmpFitness)
updateGuesses()
}
else{
clearInterval(repeat);
}
}

Related

Javascript nested loop crashes browser

I am creating a web app with Django and I require some Javascript for changing styles of dynamically generated elements. I have simplified the code to just static html and javascript.
Goal:
The code causing problems is acting on detail pages.
There are many detail pages, each representing data from a given database entry.
Each page will have 1 or more table, depending on how many protein names the database entry has.
For each table, I want to change the colour of the entry for the protein name in the table heading as well as the entry for the example_id.
Attempt:
I am using javascript to capture the example_id from the top level heading and the protein names from the table headings.
I am then capturing the nodelist of table rows and iterating through, looking for entries that match either the protein name or the example_id.
Problem:
When iterating over the nodelist of protein names taken from the table headers in a nested loop the page never loads.
HTML:
<html>
<body>
<h1 class="msaIdCatcher">Protein Record #example_id</h1>
<h2>Multiple Sequence Alignment</h2>
<h3 class= "msaProtNameCatcher">Protein_name1</h3>
<p>The following is a multiple sequence alignment (MSA) of all sequences predicted to be Protein_name1 sequences.</p>
<table>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id1</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>Protein_name1</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id3</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>example_id</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id4</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
</table>
<h3 class="msaProtNameCatcher">Protein_name2</h3>
<p>The following is a multiple sequence alignment (MSA) of all sequences predicted to be Protein_name2 sequences.</p>
<table>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id1</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id2</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id3</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>example_id</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>not_example_id4</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr class=sequenceidrow>
<th class=sequenceid>Protein_name2</th>
<td class="alignsequence">aaaaaaaaaaaaaaaaaaaa</td>
</tr>
</table>
</body>
</html>
var idTitle = document.getElementsByClassName("msaIdCatcher");
id = idTitle[0].innerHTML;
id = id.replace("Protein Record #", "");
//Get protein_names from table headers
proteinnameElements = document.getElementsByClassName("msaProtNameCatcher")
//Get table rows
var sequenceidrowElements = document.getElementsByClassName("sequenceidrow");
//Loop through table rows
for (var i = 0; i < sequenceidrowElements.length; i++) {
//Get sequence id
var sequenceidElement = sequenceidrowElements[i].getElementsByClassName("sequenceid");
idElement = sequenceidElement[0].innerHTML
//Check if ID is ID from page heading
if (idElement == id) {
//Get sequence element and change colour of ID and sequence elemnt
var alignsequenceElement = sequenceidrowElements[i].getElementsByClassName("alignsequence");
sequenceidElement[0].style.color = "#b80090";
alignsequenceElement[0].style.color = "#b80090";
}
//Loop through protein names in table headers and Check if ID in table matches protein name
//Then change colour of ID and sequence
for (var i = 0; i < proteinnameElements.length; i++) {
proteinname = proteinnameElements[i].innerHTML
if (idElement == proteinname) {
var alignsequenceElement = sequenceidrowElements[i].getElementsByClassName("alignsequence");
sequenceidElement[0].style.color = "red";
alignsequenceElement[0].style.color = "red";
}
}
}
However, when using a single protein name by making proteinname equal to the innerHTML of the first element proteinnameElements and taking away the loop nesting as follows, the page loads in a fraction of a second.
var idTitle = document.getElementsByClassName("msaIdCatcher");
id = idTitle[0].innerHTML;
id = id.replace("Protein Record #", "");
//Get protein_names from table headers
proteinnameElements = document.getElementsByClassName("msaProtNameCatcher")
proteinname = proteinnameElements[0].innerHTML
//Get table rows
var sequenceidrowElements = document.getElementsByClassName("sequenceidrow");
//Loop through table rows
for (var i = 0; i < sequenceidrowElements.length; i++) {
//Get sequence id
var sequenceidElement = sequenceidrowElements[i].getElementsByClassName("sequenceid");
idElement = sequenceidElement[0].innerHTML
//Check if ID is ID from page heading
if (idElement == id) {
//Get sequence element and change colour of ID and sequence elemnt
var alignsequenceElement = sequenceidrowElements[i].getElementsByClassName("alignsequence");
sequenceidElement[0].style.color = "#b80090";
alignsequenceElement[0].style.color = "#b80090";
}
//Loop through protein names in table headers and Check if ID in table matches protein name
//Then change colour of ID and sequence
if (idElement == proteinname) {
var alignsequenceElement = sequenceidrowElements[i].getElementsByClassName("alignsequence");
sequenceidElement[0].style.color = "red";
alignsequenceElement[0].style.color = "red";
}
}
Can someone help me understand why nesting loops in this way causes such a large difference in runtime and help me find a way to solve my problem?
Thanks!
Your inner loop begins with var i, because of how scoping works in JavaScript, it will be the same i as the outer loop, and it will be changed everytime the inner loop is run (thereby never increasing the outer loop, making it endless); it's like typing this:
var i;
for (i = 0; i < length; ++i)
{
for (i = 0; i < length2; ++i)
{
//...
}
}
Either use a different variable name for the inner loop (j is a common choice), or use the let keyword (which will ensure the variables are locally scoped), this is the let keyword (note that it's relatively recent):
for (let i = 0; i < length; ++i)
{
//...
}
Hope this helps clear things up.

How do I condition a string variable from a random generator based on the results of another random variable in javascript?

I'm new to javascript coding and wanted to run a simple command for filling in a table using the math.random function. I want to constrain one random variable based on the output of another random variable. I created a function, which I was hoping would condition the new random variable from a prior random variable based on a specific output. Any help would be appreciated.
Below is the the javascript code (I'm just trying to condition educational background based on earlier draw of occupation):
// generate string variables
var vjob = ["Retail worker", "Financial analyst"];
var vedu1 = ["Secondary", "Bachelor's", "Masters or professional degree"];
var vedu2 = ["Bachelor's", "Masters or professional degree"];
// random generator fn conditional on occupational outcome
function getEDU() {
var rand1 = Math.floor(Math.random() * vjob.length);
var rand2 = vedu1[Math.floor(Math.random() * vedu1.length)];
var rand3 = vedu2[Math.floor(Math.random() * vedu2.length)];
if (rand1 == "Financial Analyst") {
return rand1;
}
return rand2;
}
// Use math.random to randomly select traits for each dimension for Person A & Person B
traits_a = [vjob[Math.floor(Math.random() * vjob.length)],
getEDU()];
traits_b = [vjob[Math.floor(Math.random() * vjob.length)],
getEDU()];
// Create list of variables to use when setting attributes
a_list = ["a1", "a2"];
b_list = ["b1", "b2"];
// set html values in conjoint table
for(let i = 0; i < 3; i++){
document.getElementById(a_list[i]).innerHTML = traits_a[i];
document.getElementById(b_list[i]).innerHTML = traits_b[i];
}
I pass that through onto a table in html:
<table border="1px solid black" cellpadding="15" cellspacing="2" width="90%">
<tbody>
<tr>
<td></td>
<td style="font-weight:bold; font-size:1.25em; font-align:center;">Person A</td>
<td style="font-weight:bold; font-size:1.25em; font-align:center;">Person B</td>
</tr>
<tr>
<td style="font-weight:bold;">Occupation</td>
<td id="a1"></td>
<td id="b1"></td>
</tr>
<tr>
<td style="font-weight:bold;">Level of education</td>
<td id="a2"></td>
<td id="b2"></td>
</tr>
</tbody>
</table>

Iterate over cells with incrementing ids

I want to fill a table with values using Javascript/Jquery.
I have a table with incrementing ids (td-1until td-42) and I want to fill this table using JQuery/Javascript.
Currently I am using this script, but I know the error $('#td-'+i) can't work, because the ID used is build wrong: $('#td-'12) is not a valid id.
Has someone a quick fix for this? I am stuck...
for (var i = 1; i < 43; i++) {
if (i < firstDay || i >= (howMany + firstDay)) {
$('#td-'+i).value("");
} else {
$('#td-'+i).value(i-firstDay);
}
}
Use text() and it worked.
var firstDay = 3, howMany = 1;
for (var i = 1; i < 7; i++) {
if (i < firstDay || i >= (howMany + firstDay)) {
$('#td-'+i).text("");
} else {
$('#td-'+i).text(i-firstDay);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id='td-1'></td>
</tr>
<tr>
<td id='td-2'></td>
</tr>
<tr>
<td id='td-3'></td>
</tr>
<tr>
<td id='td-4'></td>
</tr>
<tr>
<td id='td-5'></td>
</tr>
<tr>
<td id='td-6'></td>
</tr>
</table>
First off, reconsider putting a large amount of IDs on elements for efficiency reasons, but putting that aside:
There's a convenience callback for .each() in jQuery, which accepts incremented (current) index and reference to element.
Depending on the DOM structure, you could do:
$('td', '#mytable').each(function(ix, tdel){
$(tdel).attr('id', 'td-' + ix).text(ix); // or $(this).attr...
});
...and see where it takes you to.

how to sum columns of html table generated from database in jsp using javascript?

I am working on my site and i want to sum the values in one column of html table using javascript over a jsp. I have found various codes which can add static data which has been put in already but when i use same thing in my code it doesnt work.
The javascript is as follows:-
<script type="text/javascript">
var debugScript = true;
function computeTableColumnTotal(tableId, colNumber)
{
var result = 0;
try
{
var tableElem = window.document.getElementById(tableId);
var tableBody = tableElem.getElementsByTagName("tbody").item(0);
var i;
var howManyRows = tableBody.rows.length;
for (i=1; i<(howManyRows-1); i++) // skip first and last row (hence i=1, and howManyRows-1)
{
var thisTrElem = tableBody.rows[i];
var thisTdElem = thisTrElem.cells[colNumber];
var thisTextNode = thisTdElem.childNodes.item(0);
if (debugScript)
{
window.alert("text is " + thisTextNode.data);
} // end if
// try to convert text to numeric
var thisNumber = parseFloat(thisTextNode.data);
// if you didn't get back the value NaN (i.e. not a number), add into result
if (!isNaN(thisNumber))
result += thisNumber;
} // end for
} // end try
catch (ex)
{
window.alert("Exception in function computeTableColumnTotal()\n" + ex);
result = 0;
}
finally
{
return result;
}
}
function finishTable()
{
if (debugScript)
window.alert("Beginning of function finishTable");
var tableElemName = "hikeTable";
//idhar column define kar raha hai wo
var totalMilesPlanned = computeTableColumnTotal("hikeTable",2);
var totalMilesHiked = computeTableColumnTotal("hikeTable",3);
try
{
var totalMilesPlannedElem = window.document.getElementById("totalMilesPlanned");
document.getElementById("total_1").innerHTML = totalMilesPlanned;
var totalMilesHikedElem = window.document.getElementById("totalMilesHiked");
document.getElementById("total_2").innerHTML = totalMilesHiked ;
}
catch (ex)
{
window.alert("Exception in function finishTable()\n" + ex);
}
return;
}
</script>
This works when html table is like
<html>
<body onload="finishTable();">
<tbody>
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td>1324</td>
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>1176576523</td>
<td>23</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>67</td>
<td>98</td>
</tr>
<tr>
<td colspan="2">Total </td>
<td id="total_1"></td>
<td id="total_2"></td>
</tr>
</tbody>
<table>
</html>
But my table is something like this :-
<html>
<body onload="finishTable();">
<tbody>
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);
while(rs.next()){
int buildarea = rs.getInt("build_area");
int numberoflevels = rs.getInt("no_of_levels");
%>
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td><%=buildarea%></td> //here a value comes from database
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>bumberoflevels</td>
<td>23</td>
</tr>
<td colspan="2">Total </td>
<td id="total_1"></td>
<td id="total_2"></td>
</tr>
</tbody>
<%}%>
<table>
</html>
Please help!!
Just some them over:
int totalBuildArea = 0;
int totalNoOfLevels = 0;
while(rs.next()){
int buildarea = rs.getInt("build_area");
int numberoflevels = rs.getInt("no_of_levels");
%>
...
...
The total row should be out of the loop.
...
...
totalBuildArea += buildarea ;
totalnumberOfLevels += numberoflevels ;
<%}%>
<td colspan="2">Total </td>
<td id="total_1"><%=totalBuildArea %></td>
<td id="total_2"><%=totalnumberOfLevels %></td>
That said,
What you are doing does not sound right at all.
For one, accessing the database from JSP is not a good idea. What you need is a good three tire architecture. You can use frameworks like struts. Or at least have your own Business Logic classes, and call them from your servlet.
Even if this is the only way for whatever reason, your JSP itself does not look correct.
Consider this:
<tr>
<td>Alapocas Woods </td>
<td>02/18/06</td>
<td><%=buildarea%></td> //here a value comes from database
<td>1</td>
</tr>
<tr>
<td>Alapocas </td>
<td>02/18/06</td>
<td>bumberoflevels</td>
<td>23</td>
Part of the data is hardcoded. Part of the data is from the database. The columns are not right. <tr>s don't end. For me this does not look like the actual code. Or it is and you have not put complete effort in giving all the details.
Try working on the JSP. Come up with a structure you want. There can be pieces that you don't know how to do. That is fine. Ask them as questions. We are here to help.
But we can help only when you ask a proper question. One simple rule: Imagine You're Trying To Answer The Question.
I leave it to you on whether you want to do the database calls using a servlet or in the JSP itself. The flow is almost the same.
First you create a class for representing the data on the UI. You have a set of (Location, Date, Planned Miles and Actual miles) and then a total of them.
You may want to create a class to represent this (I have made up the name from the id of the HTML, you may want to give a better name):
class Hike
{
private String location;
private Date date;
private Integer builtArea;
private Integer numberOfLevels;
//And their getters and setters
}
And a HikeData class
class HikeData
{
private List<Hike>;
private Integer totalBuiltArea;
private Integer totalNumberOfLevels;
//And their getters and setters
}
//The database call part is fine:
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);
//Fetch the data and populate the above classes
int totalBuiltArea = 0;
int totalNumberOfLevels = 0;
List<Hike> hikeList = new ArrayList<Hike>();
while(rs.next()){
Hike hike = new Hike();
hike.setLocation(rs.getString("location"));
hike.setDate(rs.getDate("date")));
int builtArea = rs.getInt("build_area");
hike.setBuiltArea(builtArea);
int numberOfLevels = rs.getInt("no_of_levels");
hike.setNumberOfLevels(numberOfLevels);
totalBuiltArea+= builtArea;
totalNumberOfLevels += numberOfLevels;
hikeList.add(hike);
}
HikeData hikeData = new HikeData();
hikeData.setHikeList(hikeList);
hikeData.setTotalNumberOfLevels(totalNumberOfLevels);
hikeData.setTTotalBuiltArea(totalBuiltArea);
//Add the class to request
request.setAttribute("hikeData", hikeData);
The HTML table part is now simpler:
<table id="hikeTable" align="center" border="1" bordercolor="lightslategray">
<tr>
<th scope="col">Locations</th>
<th scope="col"> Date </th>
<th >Miles (planned)</th>
<th>Miles (actual)</th>
</tr>
<%HikeData hikeData = request.getAttribute("hikeData");
for(Hike hike : hikeData.getHikeList())
{%>
<tr>
<td><%=hike.getLocation()%></td>
<td><%=hike.getDate()%></td>
<td><%=hike.getBuiltArea()%></td> //here a value comes from database
<td><%=hike.getnumberOfLevels()%></td>
</tr>
<%}>%>
<tr>
<td colspan="2">Total </td>
<td id="total_1"><%=hikeData.getTotalNumberOfLevels()%></td>
<td id="total_2"><%=hikeData.getTotalBuiltArea()%></td>
</tr>
If you are using a servlet, you move the database part to the servlet or to a service class that is called from the servlet.
If you are continuing with the JSP, you have all these in the JSP itself.
I know adding to request and then retrieving is kind of redundant but I have done so so that if you decide to move this out of the JSP, it is easier.
On a closing Note: This is definitely not the best way to write web apps. There are frameworks to make your job easier and the application maintainable and scalable. For the controller(servlet) part you can use the well known struts framework, [Spring Web flow][2], or the very simple Apache Wicket.
For the business logic part, you can use EJB3 or spring.
For database access you can use hibernate.
None of this is mandatory, but it always good to have at least a MVC framework i not the database and business logic stuff. Struts makes your life very easy.

Rearranging table in JavaScript

I want reorder table rows using JavaScript .
for example take the following dummy table:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
</tr>
</table>
I want to do this in JavaScript without using jQuery. I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row.
I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?
If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it:
<table id="mytable">
...
</table>
<script type="text/javascript">
var tbl = document.getElementById('mytable');
var rows = tbl.getElementsByTagName('tr');
var firstRow = rows[0];
var lastRow = rows[rows.length];
firstRow.parentNode.insertBefore(lastRow.parentNode.removeChild(lastRow), firstRow);
</script>
Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.
Do:
var table = ...; // Get reference to table (by ID or other means)
var lastRow = table.rows[table.rows.length - 1];
lastRow.parent.insertBefore(table.rows[0], lastRow);
The best way to solve this in Javascript is:
Give the Tr.. a unique name. for eg: X_Y,X_Z,A_Y,A_Z
Now add a hidden lable or text Box which gives the sorting order from the server i.e When the page renders I want to sort it All the Tr's that have a ID starting with A should come first and All the Z's should come second.
<asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X</label>
<asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y</label>
When the page renders..the order should be A_Z,A_Y,X_Z,X_Y
Before Rendering this is table that comes from the aspx file:
<table>
<tr id='Tr_Heading'>
<td>A</td>
<td>B</td>
</tr>
<tr id="Tr_X_Y">
<td>GH</td>
<td>GH1</td>
</tr>
<tr id="tr_X_Z">
<td>HU</td>
<td>HU1</td>
</tr>
<tr id="tr_A_Z">
<td>JI</td>
<td>JI1</td>
</tr>
<tr id="tr_A_Y">
<td>JI</td>
<td>JI1</td>
</tr>
Script:
function SortAndArrange()
{
var firstList = document.getElementById('lblFirstSortOrder').value;
var secondList = document.getElementById('lblSecondSortOrder').value;
var firstTypes = new Array();
firstTypes = firstList.split(',');
var secondLists = new Array();
secondLists = secondList.split(',');
var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]);
for (var i = 0; i<firstTypes.length; i++)
{
for (var j = 0; j< secondTypes.length;j++)
{
var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j];
var FirstSecondTrs = document.getElementById(TrName);
if (FirstSecondTrs)
{
FirstSecondTrs.parentNode.removeChild(FirstSecondTrs);
insertAfter(refNode,FirstSecondTrs);
refNode = FirstSecondTrs;
}
}
}
}
function insertAfter( referenceNode, newNode )
{
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page...
Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution.
Thanks,
Ben

Categories