The Count The Count - 3 months ago 5
HTML Question

trying to get a random number on button click

I'm trying to use javascript to get a random number in the range of 0-20 to display in a text box after the user clicks a button, but I am so far unsuccessful. What is the error in my code?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form><input name="code" id="code" type="text" value="" >
<script type="text/javascript">
function makeid()
{
var randomnumber=Math.floor(Math.random() * 20)
}
</script>
<input type="button" style="font-size:9pt" value="Generate Code" onclick="document.getElementById('code').value = makeid()">
</input>
</form>
</body>
</html>

Answer

You function needs to return a value:

function makeid() {
    return Math.floor(Math.random() * 20)
}
Comments