Results 1 to 3 of 3

Thread: Autogenerate form fields with random text

  1. #1
    Join Date
    May 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Autogenerate form fields with random text

    I have a registration form and i want to autogenerate one of the text fields with random numbers or letters , basically when user gets to the page the field is hidden but it will populate with random numbers or text...

  2. #2
    Join Date
    Feb 2008
    Posts
    81
    Thanks
    8
    Thanked 5 Times in 5 Posts

    Default

    There are millions of ways of generating random strings.
    You can use the Math.random(); function:

    Code:
    function randomString(length) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
        
        if (! length) {
            length = Math.floor(Math.random() * chars.length);
        }
        
        var str = '';
        for (var i = 0; i < length; i++) {
            str += chars[Math.floor(Math.random() * chars.length)];
        }
        return str;
    }
    Now assuming you have a hidden input as you mentioned:

    HTML Code:
    <input id="secret" type="hidden">
    Simply use DOM + our random function:

    Code:
    document.getElementById("secret").value = randomString(16);

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Do you really want random? That serves no useful purpose I can think of. You might be going for unique. If so, you could use only numbers and the date object:

    Code:
    document.getElementById("secret").value = new Date().getTime());
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •