0

我正在尝试用随机数填充文本框我目前正在一个文本框上尝试。在事件加载时,我希望文本框使用 javascript 填充随机数。

<script type="text/javascript">
    function Random() 
      {
        return Math.floor(Math.random() * 10);
      } 
</script>   

<form name="f1">
    a=      <input type="text" name="field1" /></br>
    b=      <input type="text" name="field2" /></br>
    Answer: <input type="text" name="ansfield" />

<input type="button" value="Fill"  onload()="document.getElementById('field1').value=Random()"/>

</form>
4

2 回答 2

1

只需为 html 文本元素设置 id ,因为您试图通过其 id 获取元素的值,试试这个

<form name="f1">
    a=      <input type="text" name="field1" id="field1" /></br>
    b=      <input type="text" name="field2" /></br>
    Answer: <input type="text" name="ansfield" />

    <input type="button" value="Fill" />
</form>
<script type="text/javascript">
    document.getElementById('field1').value = Math.floor(Math.random() * 10);
</script>
于 2014-10-06T13:43:11.210 回答
0

将 放在<script>HTML 的末尾并在其中设置字段值。您还缺少您的id财产input

<body>
    <form name="f1">
        a=      <input type="text" id="field1" name="field1" /></br>
        b=      <input type="text" name="field2" /></br>
        Answer: <input type="text" name="ansfield" />

        <input type="button" value="Fill" />
    </form>
    <script type="text/javascript">
        function Random() {
            return Math.floor(Math.random() * 10);
        }

        document.getElementById('field1').value = Random()
    </script>
</body>
于 2014-10-06T13:39:13.970 回答