Exploring Password Verification Techniques in JavaScript

I'm struggling with a password comparison issue in JavaScript. It was working fine on my previous project, but for some reason it's not working now. Here is the HTML code:

<form>
        <label>
            <strong>Username</strong>
            <input type="text" name="">
        </label>
        <label>
            <strong>Password</strong>
            <input type="password" name="" id="password">
        </label>
        <label>
            <strong>Confirm Password</strong>
            <input type="password" name="" id="confirmpassword"> 
        </label>
        <button class="button" type="submit" id="button" onclick="click();">Submit</button>
    </form>

And here is the corresponding JavaScript code:

function click (){
    var password =  document.getElementID('password').value,
    confirmpassword =   document.getElementID('confirmpassword').value

    if (password == ""){
        alert("Field cannot be empty.");

        
    }
    else if (password != confirmpassword){
        alert("Passwords don't match. Please try again.");
        return false

    }
    else if(password == confirmpassword){
        alert("Password Match")
        
    }
    return false
}

Answer №1

When attempting to retrieve the password field value, you have utilized getElementID, however, it is important to note that there is no function named document.getElementID.

To properly obtain the field value, you should use document.getElementById.

Answer №2

To improve your form functionality, consider including the onSubmit attribute in the form tag and invoking the function there instead of within the submit button itself. See example below:

<form name="myForm" onsubmit="return click();">

Remember to remove the onClick from the submit button

Also note that it is not getElementID, but rather getElementById()

Answer №3

Give this a shot:

HTML:

<form id="my-form">
        <label>
            <strong>Username</strong>
            <input type="text" name="">
        </label>
        <label>
            <strong>Password</strong>
            <input type="password" name="" id="pass-key">
        </label>
        <label>
            <strong>Confirm Password</strong>
            <input type="password" name="" id="confirm-pass"> 
        </label>
        <button id="unique-id">submit</button>
    </form>

JS:

var form = document.getElementById("my-form");

document.getElementById("unique-id").addEventListener("click", function () {
  var password = document.getElementById("pass-key").value,
    confirmPass = document.getElementById("confirm-pass").value;

  if (password == "") {
    alert("Field cannot be empty.");
  } else if (password != confirmPass) {
    alert("Passwords do not match. Please try again.");
    return false;
  } else if (password == confirmPass) {
    alert("Passwords Match");
    form.submit();
  }
});

Answer №4

Consider updating the name of your function because using 'click' is not effective. Try changing it to something like 'submit' for better functionality;

function submit (){
    var password =  document.getElementById('password').value,
    confirmpassword =   document.getElementById('confirmpassword').value

    if (password == ""){
        alert("Field cannot be left empty.");
        
    }
    else if (password != confirmpassword){
        alert("Passwords do not match. Please try again.");
        return false
    }
    else if(password == confirmpassword){
        alert("Password Match")
    }
    return false
}
        <label>
            <strong>Username</strong>
            <input type="text" name="">
        </label>
        <label>
            <strong>Password</strong>
            <input type="password" name="" id="password">
        </label>
        <label>
            <strong>Confirm Password</strong>
            <input type="password" name="" id="confirmpassword"> 
        </label>
        <button class="button" type="button" id="button" onclick="submit();">Submit</button>

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

Is there a way to automatically extract data from a CSV file and display it on a website using either PHP or JavaScript?

I have a web service link at www.xyz.com/abcdefg. When I visit this link, it automatically downloads a CSV file. The CSV file contains columns of data organized like this: Column A Column B Column C Column D test1 1 5 ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Encountered a problem when attempting to upload images to Cloudinary through the front-end and save the information in a MySQL database using Axios on Node JS

I am currently working on a web application using React. I have implemented a form where users can input text data and upload multiple image files. The goal is to store the submitted images on Cloudinary along with other text data in a MySQL database. Unf ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...

Utilize a function or array to send various data with an Ajax post request

Hey, I'm on the hunt for a more efficient method to send data using ajax to php for multiple users. Take a peek at my code below: $(document).ready(function(){ $("#all").click(function(){ document.getElementById('babon').click(); ...

What are some ways to transfer information seamlessly between two PHP files without the need for a page refresh?

On my webpage, I have implemented two iframes. The first iframe contains a button that, when clicked, should reload the second iframe with specific data, without reloading the first iframe. I am looking for a way to achieve this. Can anyone help? <?p ...

What is the method for accessing 'this' beyond the scope of my object?

My Jcrop initialization for a website includes my own namespace. I have a question regarding the this keyword. Whenever I need to access my base object called "aps" in any callback function, I have to wrap this in a variable (I chose the word that). Is t ...

Verifying the selection state of a dynamically generated checkbox with JavaScript

I have a table with checkboxes. Each time a button is clicked, I dynamically add new checkboxes to the table like so: var cell3 = row.insertCell(2); cell3.innerHTML = '<input type="checkBox" value=\"selected?\" style="cursor:poin ...

I have noticed that the baseline of a Span element has shifted after updating my Chrome browser to a version that begins with

Once I updated to chrome Version 108.0.5359.94 (Official Build) (64-bit) from 107.0.5304.87 (Official Build) (64-bit), the behavior of the span element changed drastically. It shifted its baseline when multiple spans were stacked on top of each other. Exp ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Running the command npm show --outdated triggers an E404 error stating that the package is not found in this registry

I am currently working on a confidential project that I prefer not to make public. Despite using node v17.3.0 and npm 8.3.0, I am facing difficulties in displaying the outdated dependencies: $ npm show --outdated npm ERR! code E404 npm ERR! 404 Not Found - ...

Looking to showcase more detailed items within ng-repeat in AngularJS

Retrieve an object from the server that resembles the following structure: "courses": [ { "id": 1, "name": "piano", "classes": [ { "id": 1, "name": "piano1", }, { ...

The ajax function in jQuery seems to be failing to retrieve data from a webmethod

I have created a jQuery function that is triggered by a DOM event: function CalculateAdhesiveWeight(volatiles1, volatiles2, testedWeight) { var volatiles1 = $('#form-textVolatiles1').val(); var volatiles2 = $('#form ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

A guide on verifying a phone number using just one character

I am looking to validate a phone number with only one character being allowed. For example, the format should be XXX-XXXXXXX where "-" is the only allowed character. Below is my validation function: function validatePhoneNumber() { if(addform.staff_m ...

Can a CSS hover effect transition modify the color scheme?

I have multiple buttons on a single page, and I want the hover effect to be applied to all of them with just one code using jQuery. Please review my code below. $(document).ready(function(){ $('.button').hover(function(){ var bc=$(this ...

Unable to open modals in Bootstrap using jQuery script: modal not popping up

My attempt to create functionality for two buttons and two modals - reserve a campsite (id="reserveButton" should open id="reserveModal") and Log in (id="loginButton" should open id="loginModal") is not working. I ha ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...