Question

Randomize HTML Table CELLS from JavaScript

Asked by: jeffreybender

Dear EE

I have HTML table and the table contains 5 Rows and 5 columns.  I want every time this HTML page is called by the user to view the cells (rows and columns) randomly. How can I do that from JavaScript? The code offered in the solution of ID: 22658210 works great to shuffle the rows each time the page is loaded but I can't figure out how to apply it to the columns as well.

THANKS

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-04-13 at 10:18:12ID23318704
Tags

randomize

,

html

,

table

,

javascript

Topics

HTMLkit

,

JavaScript

Participating Experts
3
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. How to shuffle a column of data in Excel
    I have a column of information in a specific order. I would like to shuffle it in a random order. In other words, the exact same data cell values should exist in the column, but the order should be changed in a random way. This is an analogy to shuffling a deck of cards. ...
  2. Shuffle Numbers Game Help!!!
    I am currently looking for some help on a game that allows you to shuffle numbers using JavaScript. Here is an example of code that works, but I need to have it without the input type Buttons and just have plain text. Can anyone help me out? Thanks, Banksy Code Starts Below...
  3. Shuffle banners
    How can i shuffles client banners on my site?
  4. GridView-JavaScript
    Dear Experts, I work with asp.net2.0, VS2005, C# I am using GridView this GridView contain item template Feild, this item template contain textbox control. 1 - I want to set a value to certain cell in this GridView using JavaScript. 2 - I want to know when the user press t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: JohnSixkillerPosted on 2008-04-14 at 00:12:11ID: 21348093

Hi,

I am afraid that there is no simple way to swap columns. Propably only way to do that is to cycle trough TABLE rows and swap particular cells. So randomize first row and apply the same pattern for the rest of the TABLE.

 

by: VincentPugliaPosted on 2008-04-14 at 05:26:59ID: 21349384

Hi,
   Do you want to randomize the rows and then the columns within the rows, or randomize everything (so that column 1 in row 3 becomes column 5 in row 1)?

 

by: HonorGodPosted on 2008-04-15 at 08:15:50ID: 21359447

Wow, this is certainly an interesting question.

First, we need to figure out how to "exchange" cell contents.
This is easy to say, and a bit challenging to do.  Why?  Well,
part of the reason is that cells contents (i.e., what is between
the <td> and </td>) may be non-trivial.  For example, we might
have a nested table.

Additionally, if we take a look at the DOM for something simple
like:

        <td id='target'>
          <table border='1'>
            <tr>
              <td>A</td>
              <td>B</td>
            </tr>
            <tr>
              <td>C</td>
              <td>D</td>
            </tr>
          </table>
        </td>
 
each browser may "render" this differently.  Looking at what FireFox
generates, we see that within the TD node, we have 3 children:

[ 0 ] is a text node with " "
[ 1 ] is the TABLE node
[ 2 ] is a text node with " "

Why it does it this way is not immediately obvious.

So, is there a way to "swap" two cells?

See the attached code for one way to do it.

Now, I'm going to have to think about a complete randomization of
the table contents...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Swap Cells</title>
<script type='text/javascript'>
  //------------------------------------------------------------------
  // Name: field()
  // Role: Document element lookup using specified id attribute.
  // Note: Returns a reference to the located element, or null
  //------------------------------------------------------------------
  function field( id ) {
    var e = document.getElementById( id );
    if ( !e ) {
      alert( 'Specified element not found.  id="' + id + '".' );
    }
    return e;
  }
 
  //------------------------------------------------------------------
  // Name: Swap()
  // Role: Exchange the contents of two table cells
  //------------------------------------------------------------------
  function swap( source, target ) {
    var debug = field( 'debug' );
    var td1 = field( source );
    var td2 = field( target );
    var cell1 = null;
    var cell2 = null;
    if ( td1 && td1.nodeName == 'TD' ) {
      var cell1 = td1.firstChild;
    } else {
      alert( 'element not found, or wrong type.  id="' + source + '"' );
      return;
    }
    if ( td2 && td2.nodeName == 'TD' ) {
      var cell2 = td2.firstChild;
    } else {
      alert( 'element not found, or wrong type.  id="' + target + '"' );
      return;
    }
    //----------------------------------------------------------------
    // 1. Move source contents => temp
    //----------------------------------------------------------------
    var temp = field( 'temp' );
    var kids = td1.childNodes.length;
    for ( var i = 0; i < kids; i++ ) {
      temp.appendChild( td1.firstChild );
    }
    //----------------------------------------------------------------
    // 2. Move target contents => source
    //----------------------------------------------------------------
    var kids = td2.childNodes.length;
    for ( var i = 0; i < kids; i++ ) {
      td1.appendChild( td2.firstChild );
    }
    //----------------------------------------------------------------
    // 3. Move temp contents => target
    //----------------------------------------------------------------
    var kids = temp.childNodes.length;
    for ( var i = 0; i < kids; i++ ) {
      td2.appendChild( temp.firstChild );
    }
  }
</script>
</head>
  <body>
    <table border='1' id='tbl'>
      <tr>
        <td id='source'><input type='text' value='Cell 1,1' size=8></td>
        <td>1,2</td>
        <td>1,3</td>
        <td>1,4</td>
        <td>1,5</td>
      </tr>
      <tr>
        <td>2,1</td>
        <td>2,2</td>
        <td>2,3</td>
        <td>2,4</td>
        <td>2,5</td>
      </tr>
      <tr>
        <td>3,1</td>
        <td>3,2</td>
        <td>3,3</td>
        <td>3,4</td>
        <td>3,5</td>
      </tr>
      <tr>
        <td>4,1</td>
        <td>4,2</td>
        <td>4,3</td>
        <td>4,4</td>
        <td>4,5</td>
      </tr>
      <tr>
        <td>5,1</td>
        <td>5,2</td>
        <td>5,3</td>
        <td>5,4</td>
        <td id='target'>
          <table border='1'>
            <tr>
              <td>A</td>
              <td>B</td>
            </tr>
            <tr>
              <td>C</td>
              <td>D</td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    <table border='1' style='display:none'><tr><td id='temp'></td></tr></table>
    <input type='button' value='swap' onclick='swap("source","target")'>
    <div id='debug'></div>
  </body>
</body>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:

Select allOpen in new window

 

by: HonorGodPosted on 2008-04-15 at 09:53:34ID: 21360401

If we have the data to be populated outside of the table (e.g., in another array),
we could do something like the following:

Let me know if the data exists within the table...

That would require a bit more work.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Random Cells</title>
<script type='text/javascript'>
  function field( id ) {
    var e = document.getElementById( id );
    if ( !e ) {
      alert( 'Specified element not found.  id="' + id + '"' );
    }
    return e;
  }
 
  function Randomize() {
    var before = [];
    for ( var r = 0; r < 5; r++ ) {
      for ( var c = 0; c < 5; c++ ) {
        before[ before.length++ ] = ( r + 1 ) + ',' + ( c + 1 );
      }
    }
    var after = [];
    for ( var i = before.length; i > 0; i-- ) {
      var j = Math.floor( Math.random() * ( i - 1 ) );
      after[ after.length++ ] = before[ j ];
      if ( j != before.length - 1 ) {
        before[ j ] = before[ before.length - 1 ];
      }
      before.length--;
    }
    var tbl   = document.getElementById( 'data' );
    var tbody = document.getElementsByTagName( 'TBODY' )[ 0 ];
    for ( r = i = 0; r < tbody.childNodes.length; r++ ) {
      var row = tbody.childNodes[ r ];
      if ( row.nodeName == 'TR' ) {
        for ( c = 0; c < row.cells.length; c++ ) {
          var cell = row.cells[ c ];
          var text = document.createTextNode( after[ i++ ] );
          row.childNodes[ c ].appendChild( text );
        }
      }
    }
  }
</script>
<body onload='Randomize()'>
  <table id='data' border='1'>
    <tbody>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td><td></td><td></td></tr>
    </tbody>
  </table>
</body>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:

Select allOpen in new window

 

by: jeffreybenderPosted on 2008-05-26 at 07:12:31ID: 21646530

Sorry for the long delay due to health issues. I had no idea that this shuffle of cells in a table would be so complex. Perhaps seeing the actual web page will be useful. The page I need the code for is http://www.vagliardoinspectionservice.com/realtors.htm The idea is to have the realtors names appear shuffled each time the page loads. This way, no realtor is receiving preference or priority for where they appear on the page. The code from solution 22658210 has been applied to a test page at http://www.vagliardoinspectionservice.com/test_swap.htm. I'm not a coder. Having difficulty with some of the code provided by the members that have worked so hard so far to offer a solution. If a simple to understand solution is available it would be most appreciated. THANKS !!!!

 

by: HonorGodPosted on 2008-05-26 at 07:53:40ID: 21646688

Sorry to hear that you were under the weather.  I hope that it wasn't anything
serious, and that you are completely recovered.

One of the errors in the code on your test_swap page is that the random
numbers that are generated are not checked for duplicates.  So, it is possible
for multiple table cells to have the same value.  I'm quite certain that that
particular realtor wouldn't mind in the least.  However, any whose image
weren't selected might be less than happy about it... :-)

One thing that might make the code simpler, and easier to understand would be
to have your table cells "numbered" with unique id attributes.  As shown in the
"code snippet" section (this portion uses a proportional font, so I had to put
the example there so it would look acceptable):

Then, your code could randomly assign positions (with no duplicates allowed),
and display the table.

Does this make sense?  If you want me to proceed with this, let me know.

Q: What should be done if you don't have "enough" images to fill the table?

Q: What if you have too many images to fit in the table?

Q: Would you prefer the whole table to be generated based upon the number
of images available?

// +----------+----------+----------+----------+----------+
// |          |          |          |          |          |
// | Cell  01 | Cell 02  | Cell 03  | Cell 04  | Cell 05  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+
// |          |          |          |          |          |
// | Cell  06 | Cell 07  | Cell 08  | Cell 09  | Cell 10  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+
// |          |          |          |          |          |
// | Cell  11 | Cell 12  | Cell 13  | Cell 14  | Cell 15  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+
// |          |          |          |          |          |
// | Cell  16 | Cell 17  | Cell 18  | Cell 19  | Cell 20  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+
// |          |          |          |          |          |
// | Cell  21 | Cell 22  | Cell 23  | Cell 24  | Cell 25  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: jeffreybenderPosted on 2008-06-08 at 19:20:44ID: 21740581

Now this is really getting complicated. You raise some great questions. Looks like I didn't give the problem nearly enough thought. If there are not enough images to fill the table I will stuff the empty cells with a "your name could be here" graphic (or something similar). I suppose if I have too many images for the table I would have to manually add a new row and fill any empty cells again with a place holder graphic. The page http://www.vagliardoinspectionservice.com/realtors.htm was made manually with FrontPage 2003. I don't mind manually making or adjusting the table and manually placing each realtor and place holder. Seems liike there should be an easy way to add some code (this from a non-coder :-) to an existing table. No?? Just a note of thanks again for the time and effort working on this concept. I wish I could devote more time to learning some code. I did read several online Java tutorials which leads me to believe that you have to have a very special mind to deal with code. I got a wicked headache a few hours into it. THANKS

 

by: HonorGodPosted on 2008-06-09 at 08:34:50ID: 21744001

You still don't mention from where the images are to be retrieved.

 

by: jeffreybenderPosted on 2008-06-09 at 09:33:42ID: 21744510

Images are only occasionally added at the request of the site owner when he establishes a relationship with new realtor companies. He only added 2 or 3 last year. I generally copy the realtors logo from their website and add descriptive text and an external link to open the realtor's website in a new window. All of the realtors logos are kept in \images but could be seperated from all other website images and graphics by moving them to a new folder like \realtor_images. Hope this answers the question.

 

by: HonorGodPosted on 2008-06-09 at 12:32:39ID: 21745915

The reason I asked was that I was trying to figure out the best way to
determine the list of images to be used.  Can we presume from this
latest information that it would be reasonable to have the names of
the input files as available in the JavaScript in some variable(s)?

 

by: jeffreybenderPosted on 2008-06-23 at 08:47:52ID: 21847446

I think so. I know "0" about JavaScript. I guess I can create a graphic for each realtor that also has the descriptive text. That way the script could have a single file name for each realtor.

 

by: HonorGodPosted on 2008-06-24 at 04:45:25ID: 21854585

Well, one thing that would make it easy to process the image files would be to
use a file naming convention that allows you to simply say the number of image
files available.

For example, something like:

image00.jpg
image01.jpg
image02.jpg
...

//--------------------------------------------------------------------
// Number of image files available
//--------------------------------------------------------------------
var MaxImageNum = 10;
 
//--------------------------------------------------------------------
// At this point, we could have a loop that allows us to process all
// of the image files based upon a file naming convention such as:
// - All file names begin with "image" and are of type .jpg
// - All file names have a two digit suffix, e.g., 00 through
//   MaxImageNum:
//--------------------------------------------------------------------
// This would mean that the could would expect to be able to locate
// all of the files by building the name using these expectations.
//--------------------------------------------------------------------

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: jeffreybenderPosted on 2008-09-01 at 17:45:20ID: 31448496

You have been great. I thank you for the effort. Unfortunately, my client has decided not to continue with the project. How can I award points for your efforts?

 

by: HonorGodPosted on 2008-09-02 at 06:08:18ID: 22366866

Thank you for the compliments, the grade & the points.

Good luck & have a great day

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...