I'll be honest. I'm a teacher at a school in Japan, and I don't really have much of a programming background. I'm dabbling more than anything else, but I thought it might be fun to try to make an English name generator that the kids could use for an activity. The program works just fine if I have it return the result as an alert, but what I really want to do is update the value of the textarea so that it reflects the generated name rather than "Your Name Here". I've been pouring over forums for hours and don't quite understand why what I have doesn't work as many of the solutions I've seen for dynamically changing a textarea value all offer the same advice, which is to change it as follows.
function someFunction()
{
var x=document.getElementById("id for textarea")
x.value = "new value"
}
Warning: Hand-coded and probably wrought with errors.
<script type="text/javascript">
function name_gen()
{
var randomNum;
var form = document.getElementById("nameGenForm");
var result = document.getElementById("nameSpace");
var boyNames = new Array("Adam", "Ben", "Cory", "David", "Eric", "Frank", "George",
"Harry", "Isaac", "James", "Kevin", "Lance", "Matthew",
"Nathan", "Patrick", "Quincy", "Ryan", "Sean", "Terrance",
"Vincent", "William", "Xavier", "Zach");
var girlNames = new Array("Alice", "Beth", "Catherine", "Danielle", "Erika", "Holly",
"Isabelle", "Jenny", "Kristen", "Lisa", "Mary", "Naomi",
"Patricia", "Quinn", "Rhianna", "Sarah", "Tiffany", "Wendy");
if (form.male.checked == true)
{
randomNum = Math.floor(Math.random()*boyNames.length);
name = boyNames[randomNum];
}
else if (form.female.checked == true)
{
randomNum = Math.floor(Math.random()*girlNames.length);
name = girlNames[randomNum];
}
else
{
alert("Please make a selection.");
return false;
}
alert(name);
//result.value = name;
}
</script>
And here's the accompanying HTML.
<form id="nameGenForm" action="" method="post">
<fieldset>
<legend>Random Name Generator</legend>
<input id="male" name="sex" type="radio" />
<label for="male">Male</label>
<input id="female" name="sex" type="radio" />
<label for="female">Female</label><br />
<input type="submit" value="Generate" onclick="name_gen();" />
</fieldset>
</form>
<div id="textArea">
<textarea rows="1" cols="20" id="nameSpace" readonly>Your Name Here</textarea>
</div>