0

I'm trying to output a random word into a specific html element. I'm almost there - but I think I'm messing up the part which prints the text...

Can anyone give me a tip as to where I'm going wrong ?

var txtGreeting = 10;
var randomCount = Math.round(Math.random() * (txtGreeting - 1)) + 1;
var greeting = new Array();
greeting[1] = "hello",
greeting[2] = "ciao",
greeting[3] = "welcome",
greeting[4] = "howdy",
greeting[5] = "greetings",
greeting[6] = "salut",
greeting[7] = "hallo",
greeting[8] = "hola",
greeting[9] = "Gday",
greeting[10] = "Hey",

document.getElementById("title").html = "greeting[randomCount]";
4
  • 2
    Try .innerHTML ;) So close! There's also some minor issues with your syntax for instance those ,s should be ;s. Commented May 12, 2014 at 22:45
  • adding to what @NiettheDarkAbsol said, you also don't need the "greeting[randomCount]" bit wrapped in quotes, since that will be interpreted as a literal string of text. Commented May 12, 2014 at 22:46
  • you know that you can separate variable declarations by commas, right? The way he has it isn't exactly correct...but barring that, it's pretty acceptable. like: var a =1, b =2, c =3, d = 4; Commented May 12, 2014 at 22:46
  • 1
    Stop using new Array!!! And the way you are using it is wrong: 1. It should be new Array() 2: An array starts at 0, not 1. Commented May 12, 2014 at 22:48

2 Answers 2

6

I'm just going to tidy up your code for you. What you've written was a great attempt!

var greetings = [
      "hello"
    , "ciao"
    , "welcome"
    , "howdy"
    , "greetings"
    , "salut"
    , "hallo"
    , "hola"
    , "Gday"
    , "Hey"
];
var greeting_id = Math.floor(Math.random() * greetings.length);
document.getElementById('title').innerHTML = greetings[greeting_id];

This uses an array literal, a "proper" zero-based array (makes picking a random index easier), dynamic .length property so you don't have to rewrite code just because you want to add a new greeting, and finally .innerHTML instead of just .html.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand why people use "comma-left" with array literals, but I find it so darn ugly! :)
@Xotic750 Haha! Me too, but that's how it's done at work, so sometimes I just reflexively do it... I've become one of them! Save me!
-1

just put "greeting[randomCount]" out of quotes and it should be fine.

1 Comment

Incorrect. .html is not a native Javascript function, so it will not work. (it is JQuery based)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.