JSFiddle - React, Tailwind, and code Playground
by Stalk
HTML
<form id="endlessForm">
<input type="text" name="input1" maxlength="10" />
</form>
CSS
input {
margin: 5px;
display: block;
clear: both;
font-family: monospace;
}
JavaScript
(function endlessForm(){
var endlessForm = this
this.form = document.querySelector('#endlessForm')
this.getLastInput = function(){
var nodes = form.querySelectorAll('input[type=text]');
return nodes[nodes.length - 1];
}
this.maxlength = getLastInput().maxLength
this.removeInput = function(input){
var nodes = form.querySelectorAll('input[type=text]')
if (nodes.length > 1){
input.remove()
getLastInput().focus()
}
}
this.addInput = function(evt){
var newInput = document.createElement('input')
newInput.type = 'text'
newInput.name = newName()
newInput.maxlength = maxlength
evt.target.parentNode.insertBefore(newInput, evt.target.nextSibling);
newInput.focus()
}
this.newName = function(){
var lastNumber = parseInt(this.getLastInput().name.replace(/[^0-9]/g, ''))
return 'input' + (lastNumber + 1)
}
this.form.addEventListener('keydown', function(evt){
var target = evt.target
if (target.tagName == 'INPUT' && target.type == 'text') {
//console.log(evt)
if (evt.key.length == 1
&& maxlength <= target.value.length){
addInput(evt)
} else if ((evt.key == 'Backspace' || evt.key == 'Delete')
&& target.value.length == 0) {
removeInput(target)
}
}
})
})()