Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New to the CF scene
    Join Date
    Feb 2012
    Location
    Nashville
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problems generating random letter in table

    I am working on a work project that requires a 5*5 table, that will generate random letters in each cell upon button click. I have most of the coding complete with the exception of the letter generation. I am currently generating numbers, I would even be fine with having a RandBetween(and listing the 26 letters of the alphabet) at this point.

    Any suggestions?

    Code:
    <script type="text/javascript">
    
    var random1, random2, random3, random4, random5, random6, random7, random8, random9, random10, random11, random12, random13, random14, random15, random16, random17, random18, random19, random20, random21, random22, random23, random24, random25;
    
    var randomArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    
    //generate the random characters
    
    function CreateCellData() {
    for (var i=0; i<randomArray.length; i++) {
    randomArray[i] = Math.floor(Math.random()*99 + 1); 
    }
    }

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    one way...

    Code:
    <html>
    <head>
    <style type="text/css">
    #mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    #mytable td{
    border:1px solid #000000;
    text-align:center;
    }
    </style>
    </head>
    
    <body>
    <table id="mytable">
      <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>
    </table>
    <script type="text/javascript">
    var alph = "abcdefghijklmnopqrstuvwxy".split("");
    
    tds=document.getElementById("mytable").getElementsByTagName("td")
    
    function randOrd(){
    return (Math.round(Math.random())-0.5); 
    } 
    
    function generate(){
    alph.sort(randOrd);
    for(var i=0;i<tds.length;i++){
    tds[i].innerHTML=alph[i]
    	}
    }
    </script>
    <input type="button" value="generate letters" onclick="generate()"/>
    </body>
    </html>

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,091
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb Something to consider...

    Something along these lines ... ?
    Code:
    <html>
    <head>
    <title> Untitled </title>
    </head>
    <body>
    <script type="text/javascript">
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    function randOrd() { return (Math.round(Math.random())-0.5); }
    var rndArray = alphabet.sort(randOrd);
    var str = '<table border="1"><tr>';
    for (var i=0; i<25; i++) {
      str += '<th>'+rndArray[i]+'</th>';
      if ((i % 5) == 4) { str += '</tr><tr>'; }
    }
    str += '</tr></table>';
    document.write(str);
    </script>
    </body>
    </html>

  • #4
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    You can easily get a random number betweeen 65 and 90 inclusive.
    Use that number as the character code of a letter.

    Code:
    function randomAlpha(){
    	return String.fromCharCode(65+Math.floor(Math.random()*26));
    }

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    jmrker - he asked for the grid to be generated on a button click, so document.write() is sudden death as it erases the page! Suggest the following mods to your script, including mrhoo's suggestion:-

    Code:
    <html>
    <head>
    <title> Untitled </title>
    </head>
    <body onload = "generate()">
    
    <div id = "grid"></div>
    
    <script type="text/javascript">
    
    function generate() {
    var str = '<table border="1"><tr>';
    for (var i=0; i<25; i++) {
    str += '<th>'+randomAlpha()+'</th>';
    if ((i % 5) == 4) { str += '</tr><tr>'; }
    }
    str += '</tr></table>';
    document.getElementById("grid").innerHTML = str;
    }
    
    function randomAlpha(){
    return String.fromCharCode(65+Math.floor(Math.random()*26));
    }
    
    </script>
    <br><br>
    
    <input type = "button" value = "Generate Another Grid" onclick = "generate()">
    </body>
    </html>
    Last edited by Philip M; 02-01-2012 at 08:18 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    actually I think he said he has a table, he just wants the letters generated onclick:

    Code:
    <html>
    <head>
    <style type="text/css">
    #mytable {
    border:1px solid #000000;
    border-collapse:collapse;
    width:200px;
    }
    #mytable td{
    border:1px solid #000000;
    text-align:center;
    height:30px;
    }
    </style>
    </head>
    
    <body>
    <input type="button" value="generate letters" onclick="generate()"/>
    <div id="mydiv"></div>
    <script type="text/javascript">
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    tab.id="mytable"
    var tbo=document.createElement('tbody');
    var row, cell;
    for(var i=0;i<5;i++){
    	row=document.createElement('tr');
    	for(var j=0;j<5;j++){
    		cell=document.createElement('td');
    		row.appendChild(cell);
    	}
    	tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
    
    tds=document.getElementById("mytable").getElementsByTagName("td")
    
    function randomAlpha(){
    return String.fromCharCode(65+Math.floor(Math.random()*26));
    }
    
    function generate(){
    for(var i=0;i<tds.length;i++){
    tds[i].innerHTML=randomAlpha()
    	}
    }
    </script>
    
    </body>
    </html>

  • #7
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,091
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Thumbs up

    Quote Originally Posted by Philip M View Post
    jmrker - he asked for the grid to be generated on a button click, so document.write() is sudden death as it erases the page! Suggest the following mods to your script, including mrhoo's suggestion:-
    You're right, he did say button click and I missed that in the initial reading.

    You made the exact change I would have suggested if I had read it more closely.

  • #8
    New Coder
    Join Date
    Feb 2012
    Posts
    18
    Thanks
    0
    Thanked 2 Times in 2 Posts
    1. Always use JS Lint: http://www.jslint.com/.
    2. Always use W3C validation services. HTML: http://validator.w3.org/. CSS: http://jigsaw.w3.org/css-validator/.
    3. Always use strict mode.
    4. Always use ===.
    5. Make your code more generic.
    6. Use JSBeautifier: http://www.jsbeautifier.org/.
    7. Use CSS Beautify: http://www.senchalabs.org/cssbeautify/.


    Quote Originally Posted by Sl1ce_of_L1fe View Post
    Code:
    var random1, random2, random3, random4, random5, random6, random7, random8, random9, random10, random11, random12, random13, random14, random15, random16, random17, random18, random19, random20, random21, random22, random23, random24, random25;
    Why would you do this?! Please don't.

    Quote Originally Posted by xelawho View Post
    one way...

    Code:
    <body>
    <table id="mytable">
      <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>
    </table>
    Hard to maintain. Better to generate rows and cells dynamically.

    Quote Originally Posted by xelawho View Post
    Code:
    <input type="button" value="generate letters" onclick="generate()"/>
    Quote Originally Posted by xelawho View Post
    actually I think he said he has a table, he just wants the letters generated onclick:

    Code:
    <input type="button" value="generate letters" onclick="generate()"/>
    Separate behavior from content. Separate JavaScript from HTML.

    Quote Originally Posted by jmrker View Post
    Something along these lines ... ?
    Code:
    document.write(str);
    document.write() is evil. Avoid.

    Quote Originally Posted by xelawho View Post
    Code:
    <html>
    
    ...
    
    tds[i].innerHTML=randomAlpha()
    
    ...
    
    </html>
    1. Always use a DOCTYPE.
    2. Always use textContent for text content. It is faster than innerHTML. Avoid innerHTML when you can. It is a security risk.



    Here is mine with changes:

    Code:
    <!DOCTYPE html>
    <html dir="ltr" lang="en">
        <head>
            <meta charset="utf-8"/>
            <title>Table of random alpha characters</title>
            <style>
                section
                {
                    margin: 10px;
                }
    
                #randomTable
                {
                    border: 1px solid #000000; /* Black. */
                    border-collapse: collapse;
                }
    
                #randomTable td
                {
                    border: 1px solid #000000; /* Black. */
                    text-align: center;
                    height: 50px;
                    width: 50px;
                }
            </style>
        </head>
        <body>
            <article>
                <section id="buttons">
                    <input type="button" id="generateButton" value="Generate"/>
                </section>
                <section id="result"></section>
            </article>
    
            <script>
                /*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
                (function ()
                {
                    "use strict";
    
                    function removeChildren(parent)
                    {
                        while (parent.hasChildNodes())
                        {
                            parent.removeChild(parent.firstChild);
                        }
                    }
    
                    function removeEventListenerAfterFiring(numberOfTimes, callback)
                    {
                        var remaining = numberOfTimes;
                        return function listener(event)
                        {
                            remaining -= 1;
    
                            if (remaining <= 0)
                            {
                                var target = event.target;
                                var type = event.type;
                                target.removeEventListener(type, listener, false);
                                target.removeEventListener(type, listener, true);
                            }
    
                            callback();
                        };
                    }
    
                    function createTable(id, rows, columns, generator)
                    {
                        var table = document.createElement("table");
                        table.setAttribute("id", id);
    
                        var body = document.createElement("tbody");
    
                        var r = null;
                        var c = null;
                        for (r = 0; r < rows; r += 1)
                        {
                            var row = document.createElement("tr");
    
                            for (c = 0; c < columns; c += 1)
                            {
                                var cell = document.createElement("td");
                                cell.textContent = generator();
    
                                row.appendChild(cell);
                            }
    
                            body.appendChild(row);
                        }
    
                        table.appendChild(body);
                        return table;
                    }
    
                    function fetchRandomAlphaCharacter()
                    {
                        return String.fromCharCode(65 + Math.floor(Math.random() * 26));
                    }
    
                    function initialize()
                    {
                        var resultSection = document.getElementById("result");
                        var generateButton = document.getElementById("generateButton");
    
                        generateButton.addEventListener("click", function appendTable()
                        {
                            removeChildren(resultSection);
                            resultSection.appendChild(createTable("randomTable", 5, 5, fetchRandomAlphaCharacter));
                        }, false);
                    }
    
                    window.addEventListener("DOMContentLoaded", removeEventListenerAfterFiring(1, initialize), false);
                }());
            </script>
        </body>
    </html>
    Last edited by [XP1]; 02-02-2012 at 02:57 AM.

  • #9
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    Quote Originally Posted by [XP1] View Post
    Here is mine with changes:
    nice. I'm guessing you didn't test it in IE<9, though...
    Last edited by xelawho; 02-02-2012 at 03:22 AM.

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by [XP1] View Post
    Avoid innerHTML when you can. It is a security risk.
    First I've heard of that. Explain, please.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #11
    New Coder
    Join Date
    Feb 2012
    Posts
    18
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by xelawho View Post
    nice. I'm guessing you didn't test it in IE<9, though...
    I can't install WIE9 on my computer. I can't even install all the WIEs on my computer at the same time for testing purposes.

    I shall not waste my time testing in WIE with a small demonstration.

    To quote Douglas Crockford, "IE6 must die! IE7 must die! IE8 must die! IE9 must die!".

    Douglas Crockford - "Crockford on JavaScript - Level 7: ECMAScript 5: The New Parts" (2011-03-29):
    http://www.youtube.com/watch?v=UTEqr0IlFKY&t=48m35s (48:35 minutes)

    Quote Originally Posted by Philip M View Post
    First I've heard of that. Explain, please.
    https://developer.mozilla.org/en/DOM..._consideration

    If that doesn't bother you, consider that textContent is faster than innerHTML.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by [XP1] View Post
    I can't install WIE9 on my computer. I can't even install all the WIEs on my computer at the same time for testing purposes.

    I shall not waste my time testing in WIE with a small demonstration.

    To quote Douglas Crockford, "IE6 must die! IE7 must die! IE8 must die! IE9 must die!".

    Douglas Crockford - "Crockford on JavaScript - Level 7: ECMAScript 5: The New Parts" (2011-03-29):
    http://www.youtube.com/watch?v=UTEqr0IlFKY&t=48m35s (48:35 minutes)

    https://developer.mozilla.org/en/DOM..._consideration
    Hmm. I cannot reproduce the example in IE9. </script> terminates the script.
    Code:
    <div id = "mydiv">xxxx</div>
    
    <script type="text/javascript">
    
    var name = "John"; 
    var el = document.getElementById("mydiv");
    el.innerHTML = name; // harmless  
    // ......  
    name = "<script>alert('I am John in an annoying alert!')</script>";  
    el.innerHTML = name; // alerts the text which is annoying and not really what was expected.  
    
    </script>

    If that doesn't bother you, consider that textContent is faster than innerHTML.
    To be candid, I do not care a fig if textContent is faster than innerHTML. Any difference would not be discernable.

    To quote Douglas Crockford, "IE6 must die! IE7 must die! IE8 must die! IE9 must die!".
    Is he a Taliban leader? Perhaps he needs to keep taking his tablets!
    As Keynes said, "In the long run we are all dead".

    [XP1] - may I very gently and respectfully point out that you are a newcomer to this forum (and we welcome you!), but you will not win friends or influence people if you are too forceful and dogmatic in your opinions, appear to be disagreeable, or are dismissive of long-standing members who have thousands of posts. 'Nuf said, I hope.
    Last edited by Philip M; 02-02-2012 at 08:19 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #13
    New Coder
    Join Date
    Feb 2012
    Posts
    18
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Philip M View Post
    Hmm. I cannot reproduce the example in IE9. </script> terminates the script.
    Result probably depends on the browser.

    Quote Originally Posted by Philip M View Post
    To be candid, I do not care a fig if textContent is faster than innerHTML. Any difference would not be discernable.
    It doesn't have to be about performance either.
    Using textContent clearly states your intent for you and for other programmers. It is obvious that you are dealing with text. The advantage is in readability.

    innerHTML may or may not contain just text. That may be ambiguous to other programmers.

    Quote Originally Posted by Philip M View Post
    To quote Douglas Crockford, "IE6 must die! IE7 must die! IE8 must die! IE9 must die!".
    Is he a Taliban leader? Perhaps he needs to keep taking his tablets!
    As Keynes said, "In the long run we are all dead".

    [XP1] - may I very gently and respectfully point out that you are a newcomer to this forum (and we welcome you!), but you will not win friends or influence people if you are too forceful and dogmatic in your opinions, appear to be disagreeable, or are dismissive of long-standing members who have thousands of posts. 'Nuf said, I hope.
    Douglas Crockford is famous, like a "father of JavaScript", and is a big supporter of the language.

    If you look at the context of the video, Crockford says that somewhat hesitantly. He wishes it weren't so. In the beginning, he calls IE6 the best browser of its time.

    Perhaps, the quotation was much too powerful; in which case, I receive your advice.
    Last edited by [XP1]; 02-02-2012 at 09:10 AM.

  • #14
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,980
    Thanks
    56
    Thanked 557 Times in 554 Posts
    Quote Originally Posted by [XP1] View Post
    "IE6 must die! IE7 must die! IE8 must die! IE9 must die!"
    ah, you're one of those. It's a sentiment shared by many here. Personally, I'd prefer that they stopped stubbornly making up their own rules and started adhering to standards, and it appears that that is slowly happening.

    But the fact is that IE is not some obscure little browser, and statistics show that IE8 is still more widely used than IE9, so coding things like textContent and DOMContentLoaded will result in somewhere around 15% of users staring at a blank screen, or clicking a button that does nothing.

    At which point the question of which is faster, which is more secure, which more clearly states your intent becomes moot because the first job of any code is to render a page, and if it fails to do that it has failed.

    You're free to code your pages any way you like, but I think if you are giving out code on a public forum and ignoring something as important as cross-browser compatibility, your code should come with a disclaimer, something like:
    this code will not work in any version of Internet Explorer, with the possible exception of IE9

    (although Philip M's testing puts that last statement in doubt)

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by xelawho View Post
    At which point the question of which is faster, which is more secure, which more clearly states your intent becomes moot because the first job of any code is to render a page, and if it fails to do that it has failed.
    Agreed 100% IE is still the most popular desktop browser in the world. Any page that does not work in IE is useless.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •