I found this virtual keyboard named "simple-keyboard" and it is working only for one input field. Inputs from the keyboard are getting inserted into the 1st text field only.
HTML
<input type="text" name="firstname" placeholder="Your name.." class="input">
<input type="text" name="lastname" placeholder="Your last name.." class="input">
<div class="simple-keyboard"></div>
Simple-Keyboard JS
let Keyboard = window.SimpleKeyboard.default;
let keyboard = new Keyboard({
onChange: input => onChange(input),
onKeyPress: button => onKeyPress(button)
});
// Update simple-keyboard when input is changed directly
document.querySelector(".input").addEventListener("input", event => {
keyboard.setInput(event.target.value);
});
console.log(keyboard);
function onChange(input) {
document.querySelector(".input").value = input;
console.log("Input changed", input);
}
function onKeyPress(button) {
console.log("Button pressed", button);
// If you want to handle the shift and caps lock buttons
if (button === "{shift}" || button === "{lock}") handleShift();
}
function handleShift() {
let currentLayout = keyboard.options.layoutName;
let shiftToggle = currentLayout === "default" ? "shift" : "default";
keyboard.setOptions({
layoutName: shiftToggle
});
}
Source: https://hodgef.com/simple-keyboard/demos/
How can I make it work for all the input fields with class="input"
?
The issue is because
querySelector()
only ever returns a single item matching the selector. If multiple exist only the first is returned.To fix your problem you need to use
querySelectorAll()
, which provides a collection of all matching elements, then you need to initialise the library on all inputs in that collection by looping through them.Given that comment it's possible that the library doesn't support multiple controls per instance. Instead you may need to create an entire
Keyboard
instance per control. This also needs to be done within the loop: