Hi,
I'm trying to use JavaScript to make a story out of randomly selected words from 4 arrays and then insert it into a textarea. It isn't working, can someone please tell me how to fix it.... there's an error somewhere I can't find. Thanks.

HTML

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head>
  <title>Lab Number 5</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
  <script type="text/javascript" src="script.js"></script>
</head> 
 <body class="body">
  
  <div class="header">
	 Lab Number 5
  </div>
  <div class="main">
	  <div class="content">
		<p class="one">
		  1.<form onsubmit="javascript:build(); return false;">
			  <textarea rows="7" cols="49" name="output" id="output">
			  </textarea>
			</form>
		</p>
		
	  </div>
  </div>  
 </body>
</html>

JAVASCRIPT

function getRandom()
{
	var number = Math.floor(1 + Math.random() * 5);
	return number;
}

function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function build() 
{
	var rand = getRandom();
	
	var article = new Array ("the", "a", "one", "some", "any");
	var noun = new Array ("boy", "girl", "dog", "town", "car"); 
	var verb = new Array ("drove", "jumped", "ran", "walked", "skipped"); 
	var preposition = new Array ("to", "from", "over", "under", "on");

	var story = "Once upon a time... \n";
	
	var max = 0;
	var sentence = "";
	var output;
	output = document.getElementById('output');
		
	while (max <= 20)
	{
		rand = getRandom();
		
		sentence = capitaliseFirstLetter(article[rand]) +" " +noun[rand] +" " +verb[rand] +" " +preposition[rand] +".\n";
		
		story += sentence;
		
		max++;		
	}
	story += "\nTHE END.";
	
	output.value = story;
}

Thanks for any help.

Recommended Answers

All 4 Replies

You are having only 5 elements in each array. So the random numbers you want to get generated from getRandom() should be 0,1,2,3 and 4 only.

But,

Math.floor( 1 + Math.random() * 5)

return numbers from 1 to 5 (1,2,3,4,and 5). So capitaliseFirstLetter(string) gets empty parameter sometimes.

Try

Math.floor( Math.random() * 5)

Thanks for your answer... I just solved it....
I needed to just initialize the max and not the sentence... don't know if that was the problem, but it's working now.

You are having only 5 elements in each array. So the random numbers you want to get generated from getRandom() should be 0,1,2,3 and 4 only.

But,

Math.floor( 1 + Math.random() * 5)

return numbers from 1 to 5 (1,2,3,4,and 5). So capitaliseFirstLetter(string) gets empty parameter sometimes.

Try

Math.floor( Math.random() * 5)

You're right about the random number generator.
I changed it to select from 0 - 4 instead of one to 5.
Thanks.

Welcome :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.