JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Form with randomised keys</h2>
<div>
<label>
First Name:
<input />
</label>
<label>
Last Name:
<input />
</label>
</div>
<button>
Submit
</button>
CSS
* {
font-family: sans-serif;
}
JavaScript
HTMLInputElement.prototype.insertAtCursor = function(text) {
text = text || '';
if (this.selectionStart || this.selectionStart === 0) {
let startPos = this.selectionStart;
let endPos = this.selectionEnd;
this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length);
this.selectionStart = startPos + text.length;
this.selectionEnd = startPos + text.length;
} else {
this.value += text;
}
};
const shuffle = data => {
data = data || [];
for (let i = data.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[data[i], data[j]] = [data[j], data[i]];
}
return data;
}
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const numbers = "0123456789";
const chars = [...alphabet, ...alphabet.toUpperCase(), ...numbers];
const buildCharMap = () => {
const shuffled = shuffle([...chars]);
const charMap = {};
for (let i = 0; i < chars.length; i++) {
charMap[chars[i]] = shuffled[i];
}
return charMap;
}
let charMap = buildCharMap();
document.querySelectorAll("input").forEach(input => {
input.addEventListener("keypress", e => {
const allowKeys = [
"Enter",
];
if (!(e.key in charMap)) return;
e.preventDefault();
e.target.insertAtCursor(charMap[e.key]);
});
});
document.querySelector("button").addEventListener("click", e => {
alert("Saved!");
})