Search code examples
javascripthtmlinput

How to put input value (type=text) in HTML as JavaScript function result


I'm curious on how to put input value (input=text) in HTML as JS function result.

I'm currently using this JavaScript function;

function maketeststring(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
      counter += 1;
    }
    return result;
}
console.log(maketeststring(16));

This is my input code in HTML;
<input class="test_string" type="text" id="teststring" readonly;>

Result of function 'maketeststring' is always regenerating when user is refreshing website (for example when you open website for 1st time it will be "IR5xOxAq30ZcOGku", when you refresh website it will regenerate in "Nnd2QlgSVFkjgthY". I want my input value to change whenever users is refreshing website. Thanks in advance!


Solution

  • Answering since you have additional requirements

    If you want to show the string in the field AND in console, then you need to save the result since each time you call the function you get a new string

    I wrap in a DOMContentLoaded to allow the script to be placed in the head before the HTML elements

    function maketeststring(length) {
      let result = '';
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      const charactersLength = characters.length;
      let counter = 0;
      while (counter < length) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
        counter += 1;
      }
      return result;
    }
    document.addEventListener('DOMContentLoaded', () => { // when page elements are available
      const saveString = maketeststring(16); // save the result
      console.log(saveString); // show it in console
      document.getElementById('teststring').value = saveString;
    });
    <input class="test_string" type="text" id="teststring" readonly;>