JSFiddle - React, Tailwind, and code Playground
HTML
<div id="divContent">
<input type="text" name="txt1"></input>
</div>
CSS
input {
margin-bottom:10px;
height: 20px;
width: 90%;
}
JavaScript
var MaxTextBoxes = 10;
var CurrentTextboxes = 1;
$(function () {
//answer choices
BindChoiceEvents();
});
function BindChoiceEvents() {
$('div#divContent input:text').unbind('keyup');
//bind appropriate events
$('div#divContent input:text:last').bind('keyup', BindAnswers);
var penultimateTextBox = $('div#divContent input:text:last').prev().bind('keyup', RemoveLastChoice)
}
function BindAnswers() {
var lastTxtBox = $('div#divContent input:text:last');
var numOfChars = $(lastTxtBox).val().length;
if (CurrentTextboxes < MaxTextBoxes && numOfChars > 0) {
//new answer possible, just add a new textbox
CurrentTextboxes++;
var newTxtBox = '<input type="text" id="txt' + CurrentTextboxes + '" class="myClass" />';
$(newTxtBox).insertAfter($('div#divContent input:text:last'));
//rebind
BindChoiceEvents();
}
}
function RemoveLastChoice() {
//remove if there's more than one textbox and penultimate textbox is empty
if (CurrentTextboxes != 0) {
var penultimateTxtBox = $('div#divContent input:text:last').prev();
var numOfChars = $(penultimateTxtBox).val().length;
if (numOfChars == 0) {
$('div#divContent input:text:last').remove();
CurrentTextboxes--;
//rebind
BindChoiceEvents();
}
}
}