Link to home
Start Free TrialLog in
Avatar of jeffreybender
jeffreybender

asked on

Randomize HTML Table CELLS from JavaScript

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
Avatar of JohnSixkiller
JohnSixkiller
Flag of Czechia image

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.
Avatar of VincentPuglia
VincentPuglia

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)?
Avatar of HonorGod
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>

Open in new window

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>

Open in new window

Avatar of jeffreybender

ASKER

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 !!!!
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  |
// |          |          |          |          |          |
// +----------+----------+----------+----------+----------+

Open in new window

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
You still don't mention from where the images are to be retrieved.
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.
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)?
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.
ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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?
Thank you for the compliments, the grade & the points.

Good luck & have a great day