So I’m working on an HTML page that contains a form where a user can send out an email invitation to join a website. I want a random token to be generated and sent along with the invitation, however first I want the user sending the invitation to be able to generate and see the token. Thus I’ve created a button in the HTML form to generate the token and I’m trying to get the button to call upon my token generator code I have written in JavaScript and then display the generated token within the HTML form before the user submits the invitation email. Here is my HTML for the form and the token generator button is highlighted in bold.
<div class="form-group">
<form id="invitationForm" form action="https://getform.io/f/d59e4f74-57a0-412a-a77f-c100c59142d3" method="POST">
<label class="col-md-4 control-label" for="textinput">Name</label>
<div class="col-md-4">
<input id="textinput" name="textinput" type="text" placeholder="Full Name" class="form-control input-md" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-4">
<input id="email" name="email" type="email" placeholder="" class="form-control input-md" required>
</div>
** <button onclick="token()">Generate Token</button>
<div id="result"></div>**
<p></p>
<input type="submit" value="Send Invitation">
</div>
And here is my Javascript code to generate token
function token() {
const random = size => btoa(
String.fromCharCode(
...crypto.getRandomValues(
new Uint8Array(size)
)
)
).replaceAll('+', 'x').replaceAll('/', 'I').slice(0, size)
for (let i = 5; i--;) console.log(random(16))}
How do I get the token generator, upon clicking the button, to output the token to the HTML form (ideally in a text box above the "Send Invitation" button)?
I tried adding
document.getElementById("result").innerHTML = "String.fromCharCode"
to the JavaScript code to get it to output to the HTML however that did not work.
2
Answers
First thing first, you don’t have a text box above the
Send Invitation
button. You havediv
with theid="result"
. You are already getting the desired result in the logs. You just need to use the returned value of a function to show it in aresult
div. Also, one of the mentions is about specifying the type of a button. The defaulttype
issubmit
. So, you can change that tobutton
so that your form is not sent every time you generate a new token.Solution:
You can use the output element to display the token to the user and a hidden input element to send the same token in the POST request.