Automatically Switch Font Colors to Red and Green

I am looking to automate the process of changing multiple textbox colors based on the class property.

<input type="text" Class="ChangeColor" />

<input type="text" Class="ChangeColor" />

<input type="text" Class="ChangeColor" />

Text Box 1: The font color changes to green when I input a positive value like 25.

Text Box 2: The font color switches to red when I input a negative value like -2.

Text Box 3: The font color becomes black when I input 0.

Note: I prefer not to use Unique IDs for this task.

Answer №1

Check it out, utilizing CSS classes and including "Not A Number" (NaN) as a special addition

const customClasses = ['nan', 'negative', 'zero', 'positive'];
document.querySelectorAll('input.ColorChange')
.forEach(input => input.addEventListener('input', function(event) {
  this.classList.remove(...customClasses);
  if (this.value.length) {
    this.classList.add(customClasses[(Math.sign(+this.value) + 2) || 0]);
  }
}));
.ColorChange.zero {
  color: black;
}

.ColorChange.negative {
  color: red;
}

.ColorChange.positive {
  color: green;
}

.ColorChange.nan {
  border-color: red;
}
<input type="text" Class="ColorChange" />
<input type="text" Class="ColorChange" />
<input type="text" Class="ColorChange" />

Answer №2

To retrieve the value stored in the input, JavaScript will be necessary.

After obtaining the input's value, a conditional statement can be implemented to alter the color to green when the value exceeds 25.

Answer №3

const elements = document.getElementsByClassName("ChangeColor");

Array.prototype.forEach.call(elements, (element) => {
  element.addEventListener("input", function (event) {
    if (event.target.value > 0) {
      event.target.style.color = "green";
    } else if (event.target.value < 0) {
      event.target.style.color = "red";
    } else {
      event.target.style.color = "black";
    }
  });
});
<!DOCTYPE html>
<html>
  <head>
    <title>Custom Page</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="content"></div>
    <input type="text" class="ChangeColor" />

    <input type="text" class="ChangeColor" />

    <input type="text" class="ChangeColor" />
    <script src="src/index.js"></script>
  </body>
</html>

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 retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

The lower border is unresponsive in the CSS/HTML code currently in use

Currently diving into the world of Web Development, I find myself tackling the CSS part. My latest challenge involves adding a bottom border to an element, but no matter what I try, the border just won't show up. I've scoured resources for soluti ...

What is the best approach for creating a Pagination component in React JS?

I recently started developing a web-app and I'm still learning about web development. I have received a backend response in JSON format with pagination information included: { "count": 16, "next": "http://localhost:800 ...

What is the best way to ensure an image within a Bootstrap 5 column scrolls along with the page, but does not go past

How can I ensure that the image inside "fixedContainer" follows scrolling without going below the end of <div class="col-lg-8">, especially when the sidebar has a large amount of data and requires scrolling? <link href="htt ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

extracting key-value pairs from nested arrays in javascript objects

As a beginner in javascript, I am facing an issue that may seem basic to others. Here is the json data I am working with: { "statusCode": 200, "status": "success", "data": [ [ { "city": "Alexandria", ...

What is the best way to correctly showcase dynamic pages in ExpressJS?

Within my app.js file, there exists an array of objects that is defined as follows: var people = [ {name: "Henrique Melo", username: "heenrique", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a121f1408130b0f1 ...

Is there a way to modify the default color when the header is assigned the "sticky" class?

Currently, I am in the process of building my own website and have implemented an exciting hover effect that randomly selects a color from an array and applies it when hovering over certain elements. However, once the cursor moves away, the color reverts b ...

Having trouble getting the Facebook like button to display on my website using an iframe in the markup

I gave it my all to try and get it to work, but unfortunately, I was unsuccessful. This is the approach I took. First, I followed the instructions provided on https://developers.facebook.com/docs/plugins/like-button. Next, I copied and pasted the iframe ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

What is the method for creating a clickable link using only HTML5 and CSS3 on a div?

Throughout the ages, this question has persisted, with answers that have stood the test of time. I've explored various solutions, yet none have met my expectations. I aim to create a fully clickable link for div .content1 without relying on text or ...

javascript basic image carousel

How can I modify my slider so that "slide 1" appears after "slide 3" without needing to use the return or previous button each time? I'm not very well-versed in javascript, so I thought I'd reach out for some assistance ...

What is the best way to retrieve JSON values based on a key using JavaScript, jQuery, or AngularJS?

Here is some JSON data that I need help with: var jsonData = { "title": "Testing", "settings": { "mySettings": false }, "jsonList": ["TestingList"], "testJsonVals": { "Test1": { "name": "name1", ...

"Creating a navigational bar using Bootstrap in a one-page application

I am facing an issue with Bootstrap's navbar in my single-page application. The dropdown navigation menu for mobile is not collapsing properly after clicking. Although I tried to fix it by adding data-toggle="collapse" data-target="#navbar" attributes ...

Tips for automatically disabling cloudzoom based on image width

I'm currently utilizing cloudzoom with the given markup: <div id="container"> <img id="main-image" class="cloudzoom" src="/img/image1.jpg" data-cloudzoom="variableMagnification: false, zoomOffsetX: 0, zoomPosition: 'inside', zoom ...

Is it possible for me to invoke an anonymous self-executing function from a separate scope?

I'm having an issue with calling the hello() function in ReactJS. When I try to call it, I receive an error message that says "Uncaught ReferenceError: hello is not defined". How can I go about resolving this error? This is a snippet from my index.ht ...

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...