This is my first post, anyway I’ll get straight to the point.
I have a form that when a user writes they’re name in, Javascript saves the value to the global variable “ch_name”. When I access this variable through an alert at any point on the site it always shows the correct value that I entered. However, it only works for alerts, when I try reference the user by using the variable it always shows as undefined.
I’ve tried re-ordering the code in case it hadn’t loaded correctly and this hasn’t yielded any results either. I’ve begun wondering whether I’ve referenced it right at all as I’m still fairly new to JavaScript.
As you’ll probably find out my code is a mess but here’s what I’ve got.
var ch_name; //my global variable
var data = new Array(); //I've taken a snippet out of an array of 8.
data[0] = '<p>Question 1</p>' + ch_name + "\n" + //ch_name is referenced on this line.
'<button onclick="results1()">Click Me</button>' + "\n" +
'<button onclick="results2()">Click Me</button>' + "\n" +
'<button onclick="results3()">Click Me</button>';
function charName(form) { //This is the code that changes the global variable ch_name.
ch_name = document.nameform.user.value;
ranData = Math.floor(Math.random() * data.length);
document.getElementById("placeholder").innerHTML = data[ranData];
}
The html snippet:
<form NAME="nameform" method="GET">
<p>Enter your character name:</p> <input type="text" name="user" value="" />
<input type="button" value="Start" onClick="charName(this.form)"/>
</form>
<div id="placeholder"></div>
Referencing the ch_name through an alert anywhere gives me the correct result, blank on page load and after the string is entered it gives the correct name. But anytime I reference it through the array variable it shows an undefined. This is not the full code but I’m certain there’s no conflicts in variable names etc. I’ve scanned it a good few times, I’m certain it’s just me being an idiot.
Is there a work around for this? I’m in a place ready to drop the whole code behind ch_name entirely to focus on other areas of the page.
Thanks for reading and any help.
The data won’t change the way you seem to think.
I think for you the best bet would be to replace
dataArray with a function.Now the
ch_nameparameter will be created dynamically every time you run the function. i.e. every time the button is pressed, which will update the data.How do you change the data in a page?