What steps can be taken to resolve an error message?

I needed to create an error message in a distinctive color using CSS when a user enters a letter instead of a number in a form. I successfully implemented this feature, however, I encountered an issue where the error message remains visible even after the user corrects their input by entering a number. How can I resolve this problem?

<html>
  <head>
    <style>
    #error {color: red;}
    </style>
  </head>
  <body>
    <p id="error"></p>
    <p id="demo"></p>
    <input id="demo1" type="text" />
    <button onclick="vote()"> Click here</button>
    <script>
      function vote() {
        var age = document.getElementById("demo1").value;
        if (isNaN(age)) {
          document.getElementById("error").innerHTML = "Input Error!!";
        } else {
          document.getElementById("demo").innerHTML = (age < 18) ? "Too young to vote" : "Old enough to vote";
        }
      }
    </script>
  </body>
</html>

Answer №1

Implemented the line

document.getElementById("id").innerHTML = "";
to clear existing content before proceeding with a new entry:

function checkAge() {

  var errorMsg = document.getElementById("error");
  var resultMsg = document.getElementById("result");
  
errorMsg.innerHTML = "";
resultMsg.innerHTML = "";  
  
  var age = document.getElementById("ageInput").value;
  if (isNaN(age)) {
    errorMsg.innerHTML = "Invalid input!";
  } else {
    resultMsg.innerHTML = (age < 18) ? "Too young to vote" : "Old enough to vote";
  }
}
body {
  background: lavender;  
}

#error {
  color: red;
}
<input id="ageInput" type="text" />
<button onclick="checkAge()"> Check Age </button>
<p id="error"></p><p id="result"></p>

Answer №2

One way to achieve this is by implementing a keyup event listener on the input element to validate each character as it is entered.

<input id="example" type="text" onkeyup="checkInput()" />

function checkInput() {
    if (isNaN(value)) {
        document.getElementById("errorMessage").innerHTML = "Invalid Input!";
    } else {
        document.getElementById("errorMessage").innerHTML = "";
    }
}

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

Modify the JSON file without using a library

I am dealing with a file called test.json Here is what it contains: [ { "data_on": { "vals_e": "", "vals_o": "" }, "data_off": { "vals_d": "" ...

By leveraging the require module, programmatically load the content of a JSON file in Node.js and Mocha by passing

Utilizing mocha, node js, and the cypress tool for writing test scripts has been successful in loading data from a json file with the following statement: var data = require('../../fixtures/TestData/JsonData/ABC_DEF.json'); However, attempting ...

React Apollo - Component not re-rendering when result changes

I am currently utilizing React Apollo to interact with a GraphQL backend. The function I am developing enables users to modify the admin permissions of another user. Within my setup, there are two components involved. One component houses the React Apollo ...

What is the best way to encapsulate a function that uses `this.item.findElement()` from Selenium in a separate file?

I'm currently working on setting up a Selenium Webdriver and Cucumber.js test environment using Node.js. In the homePageSteps.js file, I have a check to verify if a banner exists on a page: Then('there should be a banner', async function() ...

Moving through divisions that share a common class name using jquery

I am experimenting with a plugin that allows me to attach popups to images. My goal is to enable navigation between all popups using previous and next buttons upon clicking on a popup. Below is the element when it's displayed: <div class="imp-too ...

Activate Input by Clicking on Label in Internet Explorer version 8

I am trying to implement a widget in JQuery colorbox that allows users to load files. My approach involves using an input tag with type='file' and styling it with visibility:hidden. Additionally, I have created two labels that are styled like but ...

I must utilize the row variable obtained from my controller in order to transmit it to another controller using Ajax

When displaying a menu of categories and products for an authenticated user, I encountered a problem with the search bar. Despite wanting only certain categories/products to be displayed, the search bar was fetching products from all categories. To address ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

What is the best method to determine if a text box is filled or empty?

I need to verify whether a text box is populated with a name. If it is empty, an alert message should be shown upon clicking the submit button, and the page should not proceed with submitting the blank value. If there is a value in the text box, then that ...

The URL for Ajax is not defined

I am currently working on a function that involves fetching an XML file and making some edits to it. This is new territory for me, so I had to do some research on the best approach to accomplish this task. After some consideration, I decided to use AJAX. H ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

Utilizing Node Js and Socket.Io to develop a cutting-edge bot

Is it possible to run JavaScript with Node.js without launching Google Chrome from various proxies? Can someone provide a sample code for this task? For example, you can find a similar project here: https://github.com/huytd/agar.io-clone Another project c ...

When attempting to navigate to a different page in Next.js, the Cypress visit functionality may not function as

In my upcoming application, there are two main pages: Login and Cars. On the Cars page, users can click on a specific car to view more details about it. The URL format is as follows: /cars for the general cars page and /cars/car-id for the individual car p ...

Suspend operation to delay for ajax call within a websocket

Looking for a solution regarding a WebSocket that updates a messaged list when receiving a message. Currently using a fetch request to retrieve data from the server in order to populate the messaged list. However, facing an issue as the code needs to pau ...

Tips for resolving text center alignment problems along with other elements when hovering

When hovering over each ul li element, a new element is added to the right side of the text. The alignment of the text is centered by default, but upon hover, the alignment changes when the new element is added. However, the issue is that the alignment s ...

iPhone: Fixed position div disappearing

Currently, I am working on creating a mobile menu for my Joomla 3 site located at . The menu is functioning correctly on desktops, however, when attempting to view it on my iPhone, the menu slides in but remains invisible. Despite this, I can still tap on ...

Difficulty adapting CSS using JavaScript

I am looking to adjust the padding of my header to give it a sleeker appearance on the page. I attempted to achieve this with the code below, but it seems to have no effect: function openPage() { var i, el = document.getElementById('headbar' ...

Creating a uniform mobile version for all smartphones on a website

My website, www.sauleezy.altervista.org, is experiencing an issue that I have been unable to resolve. I have set up two different .css files for desktop (style.css) and mobile (handheld.css). In my index file, I included the following code: <meta name= ...

Eliminating attributes in mapStateToProps

When wrapping material TextField with a redux component, it is important to consider that some properties should be used in mapStateToProps only and not passed directly to the component. Otherwise, an Unknown prop warning may occur. Even specifying an unde ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...