adding a touch of flair to a form input that doesn't quite meet the

My goal is to have a red background appear when an input is invalid upon form submission.

I attempted the following code:

input:invalid {
   background-color:red;
}

While this solution worked, it caused the red background to show up as soon as the page loaded, even though the fields were empty.

I also explored another option mentioned here, but unfortunately, it did not make any difference.

Answer №1

html code snippet

<form id="myForm" action="#" method="post">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required>
  <br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required>
  <br>
  <input type="submit" value="Submit">
</form>

CSS code example

input:invalid {
  background-color: red;
}

Javascript function

var form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
  event.preventDefault();
  var inputs = form.querySelectorAll("input[required]");
  for (var i = 0; i < inputs.length; i++) {
    if (!inputs[i].checkValidity()) {
      inputs[i].classList.add("invalid");
    } else {
      inputs[i].classList.remove("invalid");
    }
  }
  if (form.checkValidity()) {
    form.submit();
  }
});


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

Attempting to transform HTML code received from the server into an image, but encountering an error while using ReactJS

This app is designed to automate the process of creating social media posts. I have a template for the vertical "Cablgram" stored in the backend, and when I make a request, it returns the HTML code for that template. However, I encounter an error when tryi ...

Issues with Jquery datatable causing column header to overlap the table header

I am facing an issue with my datatable as the table is not displaying correctly. Could someone advise me on how to troubleshoot and fix this problem? Below is the code snippet in question: $(tbName).dataTable({ "sScrollX": "100%", "sScro ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows: Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only ret ...

Issues with AngularJS have arisen, as it is currently unable to recognize and access variables as needed

As a newcomer to web design and Angular, I am trying to replicate this example, where I consume a RESTful web service and use AngularJS to display the JSON data. However, I'm facing issues with my implementation. Here's how my main.jsp file look ...

Unusual AngularJS error encountered while performing calculations on object properties

After running a specific calculation in my code, I encountered an unexpected issue. if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') { $scope.memoryTable[name][category]['total'] = $scope.memoryTabl ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

Attempting to acquire multiple responses for a single callback function from multiple requests

I have developed a calculator web application using node.js with express. My goal is to create buttons for addition, subtraction, multiplication, and division operations. While my POST request works fine with a single res.send(), I encountered an issue whe ...

Why do the async functions appear to be uncovered branches in the Jest/Istanbul coverage report?

I am encountering an issue throughout my application: When running Jest test coverage script with Istanbul, I am getting a "branch not covered" message specifically on the async function part of my well covered function. What does this message mean and how ...

Is utilizing fixed-top/fixed-bottom with inner div elements set to a fixed height the most effective strategy?

I am working on developing an app similar to stackoverflow, with fixed menu and footer panels and an inner div that creates browser scroll as needed. I'm wondering if the code below is correct for achieving this setup. The classes fixed-top/fixed-bot ...

Is there a way to verify in AngularJS whether ng-model contains a string or a numerical value?

In my Angular application, I have written a JavaScript function that checks if the value of a text field is undefined or empty, and it is working properly. $scope.checkNumber = function(user_answer){ if(user_answer == undefined){ return false; } } My ...

How to embed HTML code within PHP using a conditional variable

I've encountered an issue with a PHP code that sends emails containing HTML templates. The HTML template includes PHP variables such as Name and Email. <strong>Name: {name} </strong> As the email template is lengthy, I have included ...

A blank screen of errors pops up when attempting to update through a form

Encountering a white error screen when attempting to add an item using a form in Python / Django. I'm currently debugging the issue but lacking information. Any guidance on where to look next would be greatly appreciated.https://i.sstatic.net/daavn.pn ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...