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
You can get and set the value of an input element through the value property.
In your case:
You can read more about input element in this document:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
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