In createInput()
, will return the dynamically created text inputs, each character from the string were assigned into data-str
attr.
the outcome I need is to disable the input and assign a class "green" if data-str
and input value
matches then focus the next input, add a class "red" if it returns false...
The code below will only detect changes on first input.
Additional question: What would be the condition to apply when all inputs found a match?
str = 'hello'
function createInput(s) {
var splitStr = s.split("");
var inputs = "";
for (var i in splitStr) {
inputs = inputs + '<input id="gwInput" type="text" data-str="' + splitStr[i] + '" autocomplete="off" maxlength="1"></input>';
}
return inputs
}
$(document).on("input", "#gwInput", function() {
$this = $("#gwInput")
inputValue = $this.val();
stringValue = $this.data("str");
if (stringValue === inputValue) {
$this.prop("disabled", true).addClass("green").removeClass("red").next().focus()
} else {
$this.addClass("red")
}
});
$('.container').html(createInput(str))
input {
display: inline-block;
text-align: center;
width: 30px;
height: 30px;
border: 1px solid #aaa;
padding: 5px;
margin: 2px;
outline: 0
}
.green { border: 1px solid green; }
.red { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" />