javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provide guidance as I am still learning.

if (pwd != cpwd) {
    document.getElementById("pwd").innerHTML = "Password must match";
    document.getElementById("cpwd").innerHTML = "Password must match";
    document.getElementById("pwd").style.color = "RED";

    return false;
}

I would like to understand how to correctly use innerHTML.

Your code snippet:

<input id="pass1" type="password" placeholder="Password" style="border-radius:7px; border:2px solid #dadada;" /> <br />
<input id="pass2" type="password" placeholder="Confirm Password" style="border-radius:7px; border:2px solid #dadada;"/> <br />

<script>
function myFunction() {
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    if (pass1 != pass2) {
        document.getElementById("pass1").style.borderColor = "#E34234";
        document.getElementById("pass2").style.borderColor = "#E34234";
    }
    else {
        alert("Passwords Match!!!");
    }
}
</script>

Submit

Thanks in advance for your support and looking forward to your response.

Answer №1

In order to activate the initial code snippet linked to your inquiry, it is recommended that you employ the onBlur event associated with the "pass2" field.

Here's an illustration:

document.getElementById("pass2").onblur=function(){
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    if (pass1 != pass2) {
      document.getElementById("pass1").innerHTML="Passwords must match";
      document.getElementById("pass2").innerHTML="Passwords must match";
      document.getElementById("pass1").style.color="RED";
      return false;
     }
     return true;    
};

Alternatively, you can link it to the submit button for a different approach.

Answer №2

To implement password validation, create a new div element in the document to hold the validation response. Here's an example of how you can do this:

<div id='passwordValidation'></div>
. Once you've compared the entered passwords and determined whether they match or not, update the content of this div with the appropriate message using JavaScript like so:
document.getElementById('passwordValidation').innerHTML = "The passwords entered do not match!";

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

What is the best way to connect these functions in a sequence using promises?

A new software has been developed to extract data from an online t-shirt store and then organize the product information into a CSV file. The software consists of 3 scraping functions and 1 function for writing the data. I'm currently facing challen ...

Firebase has flagged the Google Authentication process with a message stating: Entry denied: The request made by this application

I have connected my domain to Firebase authentication and granted authorization for authentication access. If you want to test it out, feel free to visit this link signInWithPopup(auth, provider) .then((result) => { // This provides a Google Acc ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Is there a specific method for organizing cached buffer conversions in Node.js for optimal efficiency?

In a GitHub discussion, it was pointed out that the Map's .has method does not work with buffers because identical buffers are considered as distinct objects. This limitation became apparent when attempting to store buffer string conversions in a map ...

"NextAuth encounters an issue while trying to fetch the API endpoint: req.body

Trying to implement authentication in my Next.js app using NextAuth.js, I've encountered an issue with the fetching process. Here's the code snippet from the documentation: authorize: async (credentials, req) => { const res = await fetch ...

Using Jquery to locate the next div element

I've created this code snippet, but it's not functioning as expected. However, by reviewing it, you can understand my intended outcome: $('.jfmfs-alpha-separator').filter(function() { return ($(this).next().not(".hide-filtered"). ...

What is the best way to save geolocation coordinates in a Javascript array?

I am attempting to utilize HTML5 geolocation to determine a user's location and then store the latitude and longitude coordinates in an array for future use with Google Maps and SQL statements. However, when I attempt to add these coordinates to the a ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

jPlayer - Utilize the setMedia() function to define the media source URL

Having some trouble using jPlayer on Firefox 3.6 (Ubuntu) function loadmedia() { $('#jquery_jplayer_1').jPlayer('setMedia', { mp3: 'media/audio/04-Piste_4_1.mp3', }); } $(document).ready(function () { $('#jque ...

Navigating the Spine

Struggling to get routing to function properly in Backbone, I have tried my best but it still seems quite confusing. Here is a snippet of what I currently have: routes: { '' : 'home', 'home' ...

npm build issues stemming from browserlist configurations

I am encountering an issue with my create-react-app failing to build, showing the following error: ./src/index.css Module build failed: BrowserslistError: Unknown browser query `dead` at Array.forEach (<anonymous>) I have carefully reviewed my ...

Previewing posts on a single page can be done by following a few

Hello there! I have written some code in React.js I am trying to display my blog posts on a single page when the user clicks on the "read more" button. I am fetching this data from a news API and I want to show each post based on its specific ID, which i ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

What steps should be taken to address the Chrome alert stating that the deferred DOM Node cannot be identified as a valid node?

While working on my node.js project hosted on a localhost server, I've encountered an unusual warning message in the inspector. The warning states: The deferred DOM Node could not be resolved to a valid node. Typically, I use the inspector to examine ...

Error message stating: "Node.js 'readline' - Mark-compacts near heap limit are not effective. Allocation failed."

Here's the process I'm following in the code: Primarily, I am engaging in web scraping tasks. I start by reading a text file containing approximately 3500 links. Next, I iterate through each link, filter out the ones I need, and make a request ...

Attempting to retrieve an array within a Mustache JavaScript template

I'm attempting to retrieve data from a mustache array using this.location.coordinates.0: <div class="block"> <label>Location (longitude/latitude):</label> {{location.coordinates.0}}/{{location.coordinates.1}} </d ...

What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked. When hovering over an area without an element, the assigned tooltip is displayed. I would like to achieve ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

Switching from a click event to a hover event in JavaScript

I've been experimenting with animating a burger bar on hover and came across an example online that I managed to adapt for mouseenter functionality. However, I'm struggling to make it revert back to the burger bar shape once the mouse leaves on m ...