2014-10-06 21 views
0

我正在嘗試使用隨機數填充文本框我嘗試使用當前的一個文本框。在事件載入時,我希望文本框使用javascript填充隨機數。在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> 
+0

' onload()='不符合html,嘗試onload =,不確定輸入元素是否支持onload,以任何方式驗證您的HTML之前,你嘗試JS上它 – birdspider 2014-10-06 13:38:32

回答

0

<script>放在HTML的末尾並在其中設置字段值。您還缺少你inputid屬性:

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

感謝回覆我試過但不工作如何設置值? – 2014-10-06 13:43:35

+0

@SangramBarge - 我做了一個編輯,你錯過了'input'的'id'參數, – tymeJV 2014-10-06 13:44:23

+0

非常感謝,所以設置值意味着通過id設置。我感謝它現在的工作! – 2014-10-06 13:48:00

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

謝謝工作:) – 2014-10-06 13:52:40