Changing the color of text in an HTML input field using CSS and JavaScript depending on the input value

Looking for a solution!

// Getting user input values 
var input1 = parseInt(document.getElementById("input1").value);
var input2 = parseInt(document.getElementById("input2").value);
var input3 = parseFloat(document.getElementById("input3").value);
var input4 = parseFloat(document.getElementById("input4").value);
var input5 = parseInt(document.getElementById("input5").value);
var input6 = parseInt(document.getElementById("input6").value);
var input7 = parseInt(document.getElementById("input7").value);
var input8 = parseFloat(document.getElementById("input8").value);
var input9 = parseFloat(document.getElementById("input9").value);
var input10 = parseInt(document.getElementById("input10").value);

Storing inputs in an array:

var allInputs = [input1, input2, input3, input4, input5, input6, input7, input8, input9, input10];

The goal is to modify the CSS of an HTML container based on the input values, changing color to red if value is 0:

for (let i = 0; i < allInputs.length; i++) {
    if (allInputs[i] === 0) {
        document.getElementById(allInputs[i]).style.color = "red";
    } else {
        document.getElementById(allInputs[i]).style.color = "black";
    }
}

Seeking a way to resolve this issue! Currently experimenting with individual containers like input1 instead of the generic reference.

Answer №1

To change the color of inputs based on certain conditions, you can select all inputs by their class and then loop through them to add an event listener for keyup or change events. Within the callback function of the event listener, you can check the value length of the input and change the color accordingly. In the following code snippet, the text color in the input will turn red if the length of the value is greater than 10, otherwise it will be green.

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">

Answer №2

UPDATE: For best results, refer to @tacoshy 's solution


To start off, create an array of objects containing values, parser, and element. The purpose of parser is to convert the value from your HTML element (using functions like parseInt or parseFloat). Meanwhile, element represents the specific HTML/DOM element you need, reducing the need for repeated calls to document.getElementById which can lead to performance issues.

const arr = [
    { parser: parseInt, element: document.getElementById("in1") },
    { parser: parseInt, element: document.getElementById("in2") },
    { parser: parseFloat, element: document.getElementById("in3") },
    { parser: parseFloat, element: document.getElementById("in4") },
    { parser: parseInt, element: document.getElementById("in5") },
    { parser: parseInt, element: document.getElementById("in6") },
    { parser: parseInt, element: document.getElementById("in7") },
    { parser: parseFloat, element: document.getElementById("in8") },
    { parser: parseFloat, element: document.getElementById("in9") },
    { parser: parseInt, element: document.getElementById("in10") },
];

For changing colors, iterate through the array using a for-of loop in JavaScript. Utilize ES6 object destructuring to extract the parser and element variables efficiently.

Apply the designated parser to the value of each element to parse it into a numeric form.

for (const { parser, element } of arr) {
    let color = "black";

    if (parser(element.value) === 0) {
        color = "red";
    }

    element.style.color = color;
}

Answer №3

Seems overly complex. Give all elements the same class and select them using querySelectorAll. Then use forEach to loop through each element and apply the color based on a ternary conditional operator:

/* This function runs when the DOM is fully loaded */
window.addEventListener('DOMContentLoaded', function() {
  /* Grab all input elements */
  const INPUTS = document.querySelectorAll('input');
  
  function checkInputs() {
    INPUTS.forEach(input => {
      let value = parseFloat(input.value);
      input.style.color = (value === 0) ? 'red' : 'black';
    })
  };
  
  /* Call the check function at the beginning */ 
  checkInputs();
  
  /* Update colors if any of the inputs change */
  INPUTS.forEach(el => 
    el.addEventListener('change', checkInputs)
  );
})
/* Just for visual representation */
input {
  width: 5em;
  display: block;
  margin-bottom: 0.5em;
}
<input type="number" id="in1" value="0">
<input type="number" id="in2" value="5">
<input type="number" id="in3" value="0">
<input type="number" id="in4" value="5">
<input type="number" id="in5" value="5">
<input type="number" id="in6" value="0">
<input type="number" id="in7" value="0">
<input type="number" id="in8" value="5">
<input type="number" id="in9" value="0">
<input type="number" id="in10" value="0">

Answer №4

From my perspective: mixing parseFloat and parseInt values can lead to complications when trying to update colors upon value changes.

For parseInt values, the color will remain red until an integer (1 or -1) is reached. However, float numbers (0.1, 0.2, 0.3, etc.) and negative values (-0.1, -0.2, -0.3, etc.) will not encounter this issue.

Using parseInt() on non-integer values will result in conversion to 0.

Below is a snippet that may appear inelegant but helps illustrate the problem when values are altered:

The parameters "step="0.1" min="-10" max="10"" in the input field are optional.

The initial snippet aims to highlight the errors, followed by a subsequent snippet resolving the issue.

        let elements_values=[];
        function getHTMLElements(){
            for (var i=1; i <=10; i++){
                var el = "in" + i;
                elements_values.push({element:document.getElementById(el),value:0,id:i-1});
                element:document.getElementById(el).addEventListener("change",dealChange);
            }
        }
        //getElementsValues is inappropriate (refer to snippet 2)
        function getElementsValues(){
            elements_values[0].value = parseInt(elements_values[0].element.value);
            elements_values[1].value = parseInt(elements_values[1].element.value);
            elements_values[2].value = parseFloat(elements_values[2].element.value);
            elements_values[3].value = parseFloat(elements_values[3].element.value);
            elements_values[4].value = parseInt(elements_values[4].element.value);
            elements_values[5].value = parseInt(elements_values[5].element.value);
            elements_values[6].value = parseInt(elements_values[6].element.value);
            elements_values[7].value = parseFloat(elements_values[7].element.value);
            elements_values[8].value = parseFloat(elements_values[8].element.value);
            elements_values[9].value = parseInt(elements_values[9].element.value);
        }
        //see the other snippet for adjustments to this function.
        function logObjects(){
            for (var i=0; i <10; i++){
                console.log("element = " + elements_values[i].element + " value = " + elements_values[i].value + " id = " + elements_values[i].id);
            }
        }
        function styleObject(){
            for (var i = 0; i < elements_values.length; i++) {
                if (elements_values[i].value === 0) {
                    elements_values[i].element.style.color = "red";
                    elements_values[i].element.style.backgroundColor = "#cccccc";
                    elements_values[i].element.style.fontWeight = "bold";
                } else {
                    elements_values[i].element.style.color = "black";
                    elements_values[i].element.style.backgroundColor = "#eeeeee";
                    elements_values[i].element.style.fontWeight = "normal";
                }
            }
        }
        function dealChange(e){
            getElementsValues();
            styleObject();
        }
        getHTMLElements();
        getElementsValues();
        //logObjects();
        styleObject();
    <input id="in1" type="number" value="0.9" step="0.1" min="-10" max="10">
    <input id="in2" type="number" value="2" step="0.1" min="-10" max="10">
    <input id="in3" type="number" value="0.3" step="0.1" min="-10" max="10">
    <input id="in4" type="number" value="0" step="0.1" min="-10" max="10">
    <input id="in5" type="number" value="1.5" step="0.1" min="-10" max="10">
    <input id="in6" type="number" value="6.67" step="0.1" min="-10" max="10">
    <input id="in7" type="number" value="0" step="0.1" min="-10" max="10">
    <input id="in8" type="number" value="8.02" step="0.1" min="-10" max="10">
    <input id="in9" type="number" value="9.88" step="0.1" min="-10" max="10">
    <input id="in10" type="number" value="-0.6" step="0.1" min="-10" max="10">

A more concise approach that circumvents the same issues is provided below: This revised snippet effectively handles decimal numbers from 0.1 to 0.9:

The code entails an array of objects to store elements, their values, IDs, as well as functions to handle HTML elements, capture their values, present information about the objects, and apply styles based on values.

While this solution may be convoluted compared to tacoshy's response, it offers greater flexibility and scalability for managing additional elements and complex logic. Nonetheless, it might be excessive for this specific scenario.

let elements_values=[];
        function getHTMLElements(){
            for (var i=1; i <=10; i++){
                var el = "in" + i;
                elements_values.push({element:document.getElementById(el),value:0,id:i-1});
                element:document.getElementById(el).addEventListener("change",dealChange);
            }
        }
        function getElementsValues(){
            for (var i=0; i <10; i++){
                elements_values[i].value = parseFloat(elements_values[i].element.value);
            }
        }
        function logObjects(){
            for (var i=0; i <10; i++){
                console.log("element = " + elements_values[i].element + " value = " + elements_values[i].value + " id = " + elements_values[i].id);
            }
        }
        function styleObject(){
            for (var i = 0; i < elements_values.length; i++) {
                if (parseFloat(elements_values[i].value) === 0) {
                    elements_values[i].element.className = "equalZero";
                } else {
                    elements_values[i].element.className = "notEqualZero";
                }
            }
        }
        function dealChange(e){
            getElementsValues();
            styleObject();
        }
        getHTMLElements();
        getElementsValues();
        //logObjects();
        styleObject();
        .equalZero {
          color: red;
          background-color: #cccccc;
          font-weight: bold;
        }
        .notEqualZero {
          color: black;
          background-color: #eeeeee;
          font-weight: normal;
        }
    <input id="in1" type="number" value="0.9" step="0.1" min="-10" max="10">
    <input id="in2" type="number" value="2" step="0.1" min="-10" max="10">
    <input id="in3" type="number" value="0.3" step="0.1" min="-10" max="10">
    <input id="in4" type="number" value="0" step="0.1" min="-10" max="10">
    <input id="in5" type="number" value="1.5" step="0.1" min="-10" max="10">
    <input id="in6" type="number" value="6.67" step="0.1" min="-10" max="10">
    <input id="in7" type="number" value="0" step="0.1" min="-10" max="10">
    <input id="in8" type="number" value="8.02" step="0.1" min="-10" max="10">
    <input id="in9" type="number" value="9.88" step="0.1" min="-10" max="10">
    <input id="in10" type="number" value="-0.6" step="0.1" min="-10" max="10">

In refining this answer, comments were added to the getElementsValues() function within the first snippet to elucidate the issues with the initial code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for implementing $routeProvider's resolve function in electron-angular-boilerplate

I am encountering an issue with loading JSON data before entering the main controller in my project. Using this project as a template, I made alterations to only dist/app/home/home.js where the changes were implemented: angular.module('WellJournal&a ...

Does the JavaScript Map Function Operate Asynchronously?

I've been making changes to the state element properties within a map computePiePercentages(){ var denominator = 1600 if (this.state.total < 1600){ denominator = this.state.total } return this.state.pieChartData.map((item, ...

Error: The session ID is not currently active

I encountered a problem with my tests failing when running them on TFS, showing the following error: WebDriverError: No active session with ID Failed: No active session with ID Interestingly, these same tests are passing locally. Everything was working ...

What is the method for displaying the value of a textarea?

I am relatively new to the world of coding, but I have already delved into HTML, CSS, and basic DOM scripting. My goal is simple - I want to create a comment box where people can leave messages like in a guestbook. However, when I input text and click on ...

Steps for accessing the "this" keyword within the parent function

Struggling with referencing `this` within a parent function while building a basic tab system using AngularJS. It seems like I may not have a solid grasp on the fundamentals, so any guidance would be appreciated: JavaScript: $scope.tabs = { _this: th ...

How can I substitute multiple rows within numpy array?

Recently, I encountered an interesting question about manipulating arrays in Python using numpy. Here is the code snippet that sparked my curiosity: n = 3 np.random.seed(1) arr = np.random.randint(0,2, size = (n,n)) This piece of code generated the foll ...

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...

The computed properties in Vue are not receiving any values when an array is passed using v-bind

Embarking on my Vue journey with a simple example, I am attempting to calculate the sum of items based on the provided data. If you wish to explore the complete example, it can be accessed in this jsffile. Here is the component structure: Vue.component(&a ...

The issue of the footer kicking out of place in the HTML layout was successfully resolved after

I am in the process of creating a simple footer that will always stay at the bottom of the page. The content on the page will not exceed the screen size, eliminating the need for scrolling. (There are a total of 5 HTML pages, and I want the footer and head ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

Can you explain the significance of these specific HTML attributes within the button tag?

While browsing the web, I stumbled upon this HTML snippet: <button class="button--standard" mat-button mat-flat-button [disabled]=true >Disabled State</button> The combination of attributes like mat-button mat-flat-button [disabled]=true is u ...

Securing User Profiles in Firebase

I am currently working on a coding issue that involves the security of user profiles. While it doesn't involve sensitive information like payment details or personal data, it does pertain to the ownership of a profile. Currently, I store users' ...

Adjust vertical dimension using rich text editor tag

I am currently using JSF with RichFaces version v.3.3.1.GA. I am trying to decrease the height style of the rich:editor tag (using TinyMCE), but for some reason it does not seem to be changing. <rich:editor id="transactionResult" style="height: 10px;" ...

Using the ui-router to repeatedly call an AngualrJS directive

I've encountered an issue with my HTML audio player in AngularJS. When the page is refreshed, everything works perfectly - I can set the source and play audio without any problems. However, if I navigate to another state in the app and then try to loa ...

"Trouble with the external CSS file - it's not

I have a question regarding my jsp file, top.jsp, and css file, top.css. Despite specifying a background color in top.css, the color is not showing up on my top.jsp file. Code snippet from top.css: @CHARSET "ISO-8859-1"; body { background-color: bl ...

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

Unable to access content from a dictionary in Django templates

Currently, I am attempting to retrieve the value of the class method that returns a dictionary. The function is structured as follows: class GetData: def __init__(self, api_key, ip, interface): self.api_key = api_key self.asa_ip = ip ...

Share the constructor and enumeration in an npm module for exportation

My background in NPM and Node.js is limited, as my expertise lies mainly in JavaScript for web browsers. Recently, I created a JavaScript library that consists of a constructor function and an enum type. In JavaScript, enums do not exist natively, so the ...

How can JavaScript be used to activate HTML5 AppCache?

<html manifest="example.appcache"> Is it possible to use javascript to include the manifest="example.appcache" part? ...