Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-01-2012, 04:00 AM   PM User | #1
Sl1ce_of_L1fe
New to the CF scene

 
Join Date: Feb 2012
Location: Nashville
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Sl1ce_of_L1fe is an unknown quantity at this point
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); 
}
}
Sl1ce_of_L1fe is offline   Reply With Quote
Old 02-01-2012, 04:40 AM   PM User | #2
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,461
Thanks: 52
Thanked 457 Times in 455 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
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>
xelawho is offline   Reply With Quote
Old 02-01-2012, 04:52 AM   PM User | #3
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,799
Thanks: 30
Thanked 463 Times in 457 Posts
jmrker will become famous soon enough
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>
jmrker is offline   Reply With Quote
Old 02-01-2012, 05:05 AM   PM User | #4
mrhoo
Regular Coder

 
Join Date: Mar 2006
Posts: 710
Thanks: 31
Thanked 128 Times in 119 Posts
mrhoo will become famous soon enoughmrhoo will become famous soon enough
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));
}
mrhoo is offline   Reply With Quote
Old 02-01-2012, 08:13 AM   PM User | #5
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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>
__________________

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.

Last edited by Philip M; 02-01-2012 at 08:18 AM..
Philip M is offline   Reply With Quote
Old 02-01-2012, 01:09 PM   PM User | #6
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,461
Thanks: 52
Thanked 457 Times in 455 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
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>
xelawho is offline   Reply With Quote
Old 02-02-2012, 12:39 AM   PM User | #7
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,799
Thanks: 30
Thanked 463 Times in 457 Posts
jmrker will become famous soon enough
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.
jmrker is offline   Reply With Quote
Old 02-02-2012, 02:45 AM   PM User | #8
[XP1]
New Coder

 
Join Date: Feb 2012
Posts: 18
Thanks: 0
Thanked 2 Times in 2 Posts
[XP1] is an unknown quantity at this point
  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..
[XP1] is offline   Reply With Quote
Old 02-02-2012, 03:16 AM   PM User | #9
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,461
Thanks: 52
Thanked 457 Times in 455 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
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..
xelawho is offline   Reply With Quote
Old 02-02-2012, 07:24 AM   PM User | #10
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 02-02-2012, 07:48 AM   PM User | #11
[XP1]
New Coder

 
Join Date: Feb 2012
Posts: 18
Thanks: 0
Thanked 2 Times in 2 Posts
[XP1] is an unknown quantity at this point
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.
[XP1] is offline   Reply With Quote
Old 02-02-2012, 08:07 AM   PM User | #12
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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>

Quote:
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.
__________________

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.

Last edited by Philip M; 02-02-2012 at 08:19 AM..
Philip M is offline   Reply With Quote
Old 02-02-2012, 08:36 AM   PM User | #13
[XP1]
New Coder

 
Join Date: Feb 2012
Posts: 18
Thanks: 0
Thanked 2 Times in 2 Posts
[XP1] is an unknown quantity at this point
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..
[XP1] is offline   Reply With Quote
Old 02-02-2012, 01:35 PM   PM User | #14
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,461
Thanks: 52
Thanked 457 Times in 455 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
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)
xelawho is offline   Reply With Quote
Old 02-02-2012, 04:49 PM   PM User | #15
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Reply

Bookmarks

Tags
array, generate, letter, random

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:33 AM.


Advertisement
Log in to turn off these ads.