user3329255 user3329255 - 12 days ago 11
HTML Question

Generating a random number in JavaScript and passing it to an HTML input tag

My script, stored as a separate js file:

function randomNumber(len) {
var randomNumber;
var n = '';

for(var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}

return n;
}

var finalSequence = randomNumber(9);

document.write('<INPUT TYPE=TEXT NAME="ACCOUNT" VALUE='+finalSequence +' MAXLENGTH=16 SIZE=16>');


I have included this
td
tag in my html file:

<td align=left><FONT FACE="Arial,Helvetica"><script src="nexgen.js"></script>


Do you suggest that I write my script inside the html file itself?

I would like to display the generated random number using an
input
tag, such as that below. How do I do this?

<INPUT TYPE=TEXT NAME="ACCOUNT" VALUE= ??? MAXLENGTH=16 SIZE=16>


Update:

I am combining the JavaScript and html in one html file as follows. Please see if you can find any mistakes because the number generated is not being displayed on html page.

Javascript part:

function randomNumber(len) {
var randomNumber;
var n = '';

for(var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}

document.getElementById("ACCOUNT").value = n;
return n;
}


HTML part:

<tr>
<td><FONT FACE="Arial,Helvetica" color="red"> Transaction ID: </font></td>
<td align=left>
<FONT FACE="Arial,Helvetica">
<script> randomNumber(9); </script>
<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE="" MAXLENGTH=16 SIZE=16 readonly>
</font>
</td>
</tr>

Answer

Assign an ID to your input element, then in your JavaScript, assign the generated value to that element.

Html be like:

<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE=""  MAXLENGTH=16 SIZE=16>

JavaScript be like:

function randomNumber(len) {
    var randomNumber;
    var n = '';

    for(var count = 0; count < len; count++) {
        randomNumber = Math.floor(Math.random() * 10);
        n += randomNumber.toString();
    }
    return n;
}

document.getElementById("ACCOUNT").value = randomNumber(9);

Working jsFiddle.

Comments