-2

I need to make my textbox (html) show a random string on load.

The string must be like XXXX-XXXX-XXXX-XXXX The X's could be A-Z and 1-9 meaning letters and numbers. This should be generated on random and shown in a textbox when the page loads.

Any help? Nothing worked so far.

Eddy
  • 21
  • 5
  • This post might be of some help: http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript – gongzhitaao Mar 23 '13 at 23:14
  • Are you saying you're not sure how to pre-load a text field? – Jonathan M Mar 23 '13 at 23:16
  • @EdrisMir Do you use jQuery or just pure js? – gongzhitaao Mar 23 '13 at 23:16
  • If you use jQuery: http://api.jquery.com/ready/. If not, pick one from :http://stackoverflow.com/questions/191157/window-onload-vs-body-onload – gongzhitaao Mar 23 '13 at 23:17
  • @Edris, please put *some* work into this before asking. Not knowing how to load a value to a textbox just shows you didn't even *try* to solve this on your own. You could have googled the answer, man. – Jonathan M Mar 23 '13 at 23:20

1 Answers1

1

Here's an implementation:

HTML:

 <input id="result" type="text>

Code:

function rand() {
    document.getElementById("result").value = generateRandStr();
}

function generateRandStr() {
    var candidates = "ABCDEFGHIJKLMNOPQRSTUVWXY123456789";
    var result = "", rand;
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            rand = Math.floor(Math.random() * candidates.length);
            result += candidates.charAt(rand);
        }
        if (i != 3) {
            result += "-";
        }
    }
    return result;
}

Working demo: http://jsfiddle.net/jfriend00/f3VSs/

jfriend00
  • 683,504
  • 96
  • 985
  • 979