I need to generate a random number on every web page load and store that number in a hidden form field (id="field10"). Following is my code but its wrong. Quick help is highly appreciated.
<script type='text/javascript'>
function test(final){
var min = 1;
var max = 9999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
var timeNow = new Date().getTime();
var final = num+'_'+timeNow;
document.getElementById('field10').value=test(final);
}
window.onload = test;
</script>
Lot of issues. Will give a quicker solution:
function test() {
var min = 1;
var max = 9999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
var timeNow = new Date().getTime();
document.getElementById('field10').value = num + '_' + timeNow;
}
window.onload = test;
I just removed few lines, which are unnecessary. This will work well. A glimpse of what I have done:
final
variable (might cause troubles sometimes). value
to the element. Snippet
function test() { var min = 1; var max = 9999999999; var num = Math.floor(Math.random() * (max - min + 1)) + min; var timeNow = new Date().getTime(); document.getElementById('field10').value = num + '_' + timeNow; } window.onload = test; setTimeout(function () { console.log(document.getElementById('field10').value); }, 500);
<input type="hidden" id="field10" />
As a best practice, always put your scripts just before your closing body
tag. You will not need to do the window.onload
thing if you follow this as the DOM will already be loaded by then. Though window.onload
might be necessary in some cases.
function randomNumber() { var min = 1; var max = 9999999999; return Math.floor(Math.random() * (max - min + 1)) + min; } document.getElementById('field10').value = randomNumber() + new Date().getTime();
<!-- add type="hidden", i omitted here so you can see the results --> <input id="field10">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.