How to Generate Random Data using Chance.js in Javascript

In this tutorial, you will learn how to use chance.js to generate fake data.  Chance.js is library to generate random or fake data in easy way.  Its not something which is widely popular like faker.js but still does the job. HTML, javascript and CSS code is given below.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <input type="text" id="firstname" placeholder="Enter First Name">
        <input type="text" id="lastname" placeholder="Enter Last Name">
        <input type="date" id="dob">
        <input type="text" id="website" placeholder="Enter Website">
        <textarea id="bio" rows="4" placeholder="Enter Bio"></textarea>
        <button>Generate</button>        
    </div>
    <script src="http://chancejs.com/chance.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

CSS:

div {
    display: flex;
    flex-direction: column;
    width: 30%;
    margin: auto;
}

input, button, textarea{
    margin: 5px;
    padding: 10px 20px;
}

Javascript:

let firstname = document.querySelector('#firstname');
let lastname = document.querySelector('#lastname');
let dob = document.querySelector('#dob');
let website = document.querySelector('#website');
let bio = document.querySelector('#bio');
let btnGenerate = document.querySelector('button');

btnGenerate.addEventListener('click', () => {
    firstname.value = chance.first({gender:'male'});
    lastname.value = chance.last();
    dob.valueAsDate = chance.birthday();
    website.value = chance.domain({tld: 'com'});
    bio.value = chance.sentence({words:20});    
});

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •