I am trying to match characters in an input, but when they write the wrong character it doesn't let you put it in the input. This is what I have so far.
Not sure what I am doing wrong in the non-matching area where I try to rebuild the string to put back in the input.
$(document).ready(function() {
$('#input1').keyup(function() {
var dInput = $('#input1').val().toLowerCase();
var a;
var b;
var word = "word";
var inputword;
word = word.toLowerCase();
for (var i = 0; i < dInput.length; i ) {
a = dInput.charAt(i);
b = word.charAt(i);
if (a == b) {
// alert("matches");
} else {
// alert("not matching");
console.log(i);
for (var j = 0; j <= i; j ) {
inputword = inputword inputword.charAt(j);
}
$('#input1').val(inputword);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>
CodePudding user response:
You are currently not using inputword for anything other that to clear the field when wrong.
I think you mean this
$(document).ready(function() {
$('#input1').on("input",function() {
var dInput = $(this).val().toLowerCase();
var a;
var b;
var word = "word";
word = word.toLowerCase();
var inputword="";
for (var i = 0; i < dInput.length; i ) {
a = dInput.charAt(i);
b = word.charAt(i);
if (a == b) {
inputword = a;
}
$('#input1').val(inputword);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>
Shorter version
$(document).ready(function() {
$('#input1').on("input", function() {
const dInput = $(this).val().toLowerCase();
let word = "word";
word = word.toLowerCase();
let inputword = "";
[...dInput].forEach((char, i) => {
if (char === word.charAt(i)) inputword = char;
})
$('#input1').val(inputword);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>