1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How do I use this code with a button and form

Discussion in 'HTML & JavaScript' started by cookiemonste, Mar 4, 2012.

  1. cookiemonste

    cookiemonste Jr. VIP Jr. VIP Premium Member

    Joined:
    Aug 9, 2009
    Messages:
    209
    Likes Received:
    91
    I'm a javascript newbie and I want to use a code that generates a random string when you click a button. here is the code

    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;
    }
    
    // generate a random string of random length
    randomString();
    
    // generate a random string of length 8
    randomString(8);
     
  2. jamb0ss

    jamb0ss Junior Member

    Joined:
    Feb 9, 2012
    Messages:
    125
    Likes Received:
    45
    Occupation:
    Bots programming
    Example:

    Code:
    <html>
    
    <head>
    
    <script type="text/javascript">
    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)];
        }
        document.getElementById("demo").innerHTML=str;
    }
    </script>
    
    </head>
    
    <body>
    
    <p id="demo">Place for string</p>
    <button type="button" onclick="randomString(3)">Generate string (length=3)</button>
    <button type="button" onclick="randomString(8)">Generate string (length=8)</button>
    
    </body>
    
    </html>
    
     
    • Thanks Thanks x 1
    Last edited: Mar 4, 2012