I’d like to write a code that compares in “real time” the world that the user introduce in an input box with a given word (i.e “house”). When the letter written is correct, the whole word is in blue, when the user introduce a wrong letter the word becomes red.
This is the html:
<input id='inputtype' onkeyup='return validateAsYouType(this);' />
EDIT: Solved! Here is the solution:
<script type="text/javascript" >
function validateAsYouType(inputElementId)
{
var val = inputElementId.value;
var randomWord = "house";
if (val.length <= randomWord.length && val == randomWord.substr(0, val.length)) {
document.getElementById("inputtype").style.color="blue"; // If right, put it in blue
}
else { document.getElementById("inputtype").style.color="red"; // If wrong, put it in red
}
if( val == randomWord)
{
document.getElementById("inputtype").style.color="#339933"; // If right, put it in green
}
}
Check that the typed word is not longer than the given word, and that the typed word so far is the same as the corresponding letters in the given word:
You would also need an
elsefor theifstatement to also change the color when the word is wrong.