skip to Main Content

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!

2

Answers


  1. You can get and set the value of an input element through the value property.
    In your case:

    document.getElementById("teststring").value = "new value";
    

    You can read more about input element in this document:
    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input

    Login or Signup to reply.
  2. 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;>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search