Use JavaScript to adjust the text color in (CSS) of an input field (HTML) based on the input value
P粉022140576
P粉022140576 2023-09-03 09:53:55
0
1
543
<p>I have a piece of code that gets 10 input values ​​(integers and floats) from the user: </p> <pre class="brush:php;toolbar:false;">var in1 = parseInt(document.getElementById("in1").value); var in2 = parseInt(document.getElementById("in2").value); var in3 = parseFloat(document.getElementById("in3").value); var in4 = parseFloat(document.getElementById("in4").value); var in5 = parseInt(document.getElementById("in5").value); var in6 = parseInt(document.getElementById("in6").value); var in7 = parseInt(document.getElementById("in7").value); var in8 = parseFloat(document.getElementById("in8").value); var in9 = parseFloat(document.getElementById("in9").value); var in10 = parseInt(document.getElementById("in10").value);</pre> <p>Then I put all the inputs into an array to make them easier to work with: </p> <pre class="brush:php;toolbar:false;">var arr = [in1, in2, in3, in4, in5, in6, in7, in8, in9, in10];</pre> <p>The idea is to adjust the CSS of the HTML container by iterating through the values, and adjust the specific container whose value is equal to 0. </p> <pre class="brush:php;toolbar:false;">for (let i = 0; i < arr.length; i ) { if (arr[i] === 0) { document.getElementById(**container of the corresponding arr[i] value**).style.color = "red"; } else { document.getElementById(**container of the corresponding arr[i] value**).style.color = "black"; } }</pre> <p>Now how do I solve this problem? </p> <p>If I just use one container, say <code>in1</code>, I can get the code to run, so if I put <code>("in1")</code> instead of < ;/ p> <pre class="brush:php;toolbar:false;">(**container of the corresponding arr[i] value**)</pre></p>
P粉022140576
P粉022140576

reply all(1)
P粉391677921

You can select all inputs by class and then iterate over them. Add an event listener on key press or change. In the event callback you can change the color based on the condition you want to check. In this example, the text in the input changes color based on the length of the value.

const inputs = document.getElementsByClassName("colorInput")

for (let i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener (
    "keyup",
    (event) => {
      event.target.style.color = event.target.value.length > 10 ? "red" : "green"
    }
  )
}
<input type="text" class="colorInput">
<input type="text" class="colorInput">
<input type="text" class="colorInput">
<input type="text" class="colorInput">
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template