javascript - trying to get a random number on button click - Stack Overflow

I'm trying to use javascript to get a random number in the range of 0-20 to display in a text box

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" ".dtd">
<html xmlns="">

<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>

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/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3/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>
Share Improve this question asked Aug 1, 2012 at 3:14 The CountThe Count 1811 gold badge4 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

You function needs to return a value:

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

You function does not return a value, which is why the input is being set to undefined.

Try this instead:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745255285a4618917.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信