I'm looking for a way to change the style of an element, (like the <body>) when not just text, but specific number like "5214" or something is entered in an <input>. With my current code, a Uncaught TypeError: Cannot set properties of undefined (setting 'innerText') gets thrown. How can I fix it? The error is on line 3. I saw something like this on an ADT security system panel, but was instead using an <input type="hidden">. There were using 4 <span> elements too.
HTML CSS JS
const inputField = document.getElementsByClassName("doSomething");
if(inputField[0].innerText = "5214") {
document.getElementsByTagName("body").style.backgroundColor = "lime";
}
input {
background-color: #ffffff;
}
<label>Numbers only:</label><input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />
<br>
<label>Numbers and decimal points only:</label>
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
There are many problems to address in that code.
doSomethingin your javascript. Thus, there are currently NO elements of classdoSomething, which is whydocument.getElementsByClassName("doSomething")returnsundefined.inputField[0].innerText = "5214", you are not comparing both values to check if they are equal. You are assigning. Wrong operator. For comparison, you need to use==.innerTextproperty, since they don't work like text elements. Instead, you need to usevalue.document.getElementsByTagName("body")would return an array, not the only body element you have, because you could have many. So, presuming you only have one body tag, you could dodocument.getElementsByTagName("body")[0].keyup, notkeypress, because the value doesn't change before thekeypress. It only does that beforekeyup. So you are checking the previous value withkeypress, not the current. Therefore, you must useonkeyup.document.getElementsByTagName("body")[0].style, as long as you have only one body tag (which you should), you should instead saydocument.body.style. Obviously, the second one is easier, simpler and makes more sense than the first.Here is the final code which works: