Ways to display success message following JavaScript validation

I've been working on creating a form that displays a success message after JavaScript validation checks are successful. To show the success message, I'm utilizing Bootstrap alert. I split my code into two files - one for common validation functions and another to check if validation is true. In the second file, I attempted to use a conditional statement to display the success message when valid is true, but it's not functioning as expected. What type of condition should I implement to ensure the success message appears?

Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    ...
    </body>
</html>

Style

*{
    ...
}

.form{
    margin: 50px;
    ...
}

...

validationCommon.js

function resetErrors(inputs, errorTexts, errorInfo) {
    ...
}

...

validationMovieForm.js


function validateForm() {
    ...
}

Answer №1

  • Forget about manually setting the .info div to display:none; in CSS - just utilize the bootstrap class .d-none.
  • When validation succeeds, skip adding a .show class and simply remove the .d-none class.
  • After successful validation, you're attaching a new event handler which necessitates submitting the form again for the new code to execute. Avoid this by removing the additional event handler altogether.
  • Don't forget to prevent the form from reloading upon successful validation by returning false. Otherwise, your info div won't be displayed as expected.

// updatedValidation.js

function resetErrors(inputs, errorTexts, errorInfo) {
  for (let i = 0; i < inputs.length; i++) {
    inputs[i].classList.remove("error-input");
  }
  for (let i = 0; i < errorTexts.length; i++) {
    errorTexts[i].innerText = "";
  }
  errorInfo.innerText = "";
}

// more functions...

function validateForm() {

  const form = document.querySelector('form');
  const message = document.getElementById('info');

  const movieNameInput = document.getElementById('movieName');
  const premiereInput = document.getElementById('premiere');
  const typeInput = document.getElementById('type');
  const priceInput = document.getElementById('price');

  const errorMovieName = document.getElementById('errorMovieName');
  const errorPremiere = document.getElementById('errorPremiere');
  const errorType = document.getElementById('errorType');
  const errorPrice = document.getElementById('errorPrice');
  const errorsSummary = document.getElementById('errorsSummary');

  let valid = true;
  resetErrors([movieNameInput, premiereInput, typeInput, priceInput], [errorMovieName, errorPremiere, errorType, errorPrice], errorsSummary);

  // validation checks...

  if (valid) {
    message.classList.remove('d-none');
  }

  if (!valid) {
    errorsSummary.innerText = "Errors found in the form";
  }

  return false;

}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Updated CSS styles */

<!-- Relevant HTML structure -->

Answer №2

Utilize JavaScript to apply CSS styles to the success message:
display:

/* target element */ .style.display = 'block';

hide:

/* target element */ .style.display = 'none';

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

Interactive material design drop-down menu

Currently, I am working on a dynamic drop-down menu that utilizes material-ui js. However, I have encountered an issue where clicking on one menu opens all the menus simultaneously, and vice versa when trying to close them. If you would like to view the c ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is t ...

Applying CSS styles to a shadow DOM element will not produce the desired visual

I'm encountering an issue while attempting to apply CSS to an element within a shadow-root by adding a class to it. In my Angular component, I have the following code: CSS .test { border: 1px solid red; } TS document.getElementById('my-div&a ...

Swap out the hyperlink text for a dropdown menu when clicked and then revert back

Is there a way to dynamically switch between a label/text and a Kendo Combobox in a div using JavaScript when clicking on the text? The desired functionality includes: Clicking on the text displays the combobox, clicking away from it hides the combobox a ...

Is there a way to track and detect alterations to an element using JavaScript or jQuery

Can I detect the addition of a specific CSS class to an element without having to create a new event? ...

What is the best way to retrieve the responseText using the jQuery.getJSON method within JavaScript?

I am currently facing an issue where I am attempting to retrieve information from a JSON file located in my directory by utilizing the jQuery.getJSON method. Unfortunately, when I try to access the object shown in the image, I am unable to extract the resp ...

What is the best way to align the checkbox and label in a React form?

I've been struggling to align the labels next to the checkboxes on this form. I'm currently utilizing React with React-Hook-Form for validation and state management (you can find the code on GitHub: https://github.com/cipdv/ciprmt-mern/blob/main/ ...

Guide to transmitting HTML form information to a different web server with the click of a button

I operate two distinct web servers. One is responsible for the front-end (example.com), and the other manages the back-end (api.example.com). On my front-end server (example.com), there is a simple HTML website with a form that includes an input field and ...

Having issues with Vue.js v-repeat not displaying any content

I have just started learning about vue.js. I attempted to display a simple list, but it is not showing anything. Here is my code: <html> <head> <title>VUE Series</title> <link rel="stylesheet" type="text/css" ...

Is the displayed Cyrillic string in the incorrect character set?

I am facing an issue with extracting a value from a decoded JSON response obtained from a Russian API. The value within the JSON = Object268 Initially, it appeared as: Объект 268 After including <meta charset="utf-8"> in my html ...

Utilize useEffect to track a single property that relies on the values of several other properties

Below is a snippet of code: const MyComponent: React.FC<MyComponentProps> = ({ trackMyChanges, iChangeEverySecond }) => { // React Hook useEffect has missing dependencies: 'iChangeEverySecond' useEffect(() => { ...

Understanding how to properly handle the data sent by an ajax request in a NodeJS server

I currently have an array called passedWord = ['a', 'bbb']. I am then making an AJAX request to send this array to a Node.js server. Upon receiving the array on the server, Body Parser returns the following object: { name: 'abc&ap ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...

Using HTML to position multiple lines of text alongside an image

I have multiple lines of content and hyperlinks. Additionally, there is an image included. I am looking to have the text aligned on the left with the image on the far right, positioned next to the text. While I attempted to use flexblocks to center everyt ...

Mapping object data within an object in React: A step-by-step guide

Within my React project, I am retrieving data from a JSON source like so: https://i.sstatic.net/fEZFL.jpg The simplified JSON data appears as: const listData = [ { "_id": "abscdf456", "bucket": { code: "videos" }, "contents": [{}, {} ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

Browsing through dual snap points simultaneously on Google Chrome

I'm currently developing a website that incorporates scroll snapping for 3 viewport-sized <section> elements set up like so: html, body { scroll-behavior: smooth; scroll-snap-type: mandatory; scroll-snap-points-y: repeat(100vh); scrol ...

There is a mismatch in the host name: please consider using a domain name (e.g., https://myname.myorg.com) instead of https://localhost

My current setup involves an HTML application that sends an AJAX request to a Qt C++ HTTP Server running on my local computer, hosted at "https://localhost:8081". However, I am facing an issue with a host name mismatch causing the AJAX request to fail. Is ...