How can I validate a password input in a form on click and reveal a hidden div on the same page without refreshing?

I've been attempting to create a password-only form that reveals a hidden div on the same page when the correct password is entered. I want to avoid reloading the page, but I'm unsure of how to achieve this.

function checkPassword() {
  var confirmPassword = "admin";
  var password = document.getElementById("pass").value;
  if (password == confirmPassword) {
    var x = document.querySelector('.hidden');
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      alert('Try again.');
      x.style.display = "none";
    }
  }
}
.hidden {
  display: none;
}
<form method="post">
  <label for="pswd">Enter Password</label>
  <input type="password" id="pass">
  <input type="button" value="Go" onclick="checkPassword();" /></form>
<div class="hidden">
  <p>This section should only be visible to users who know the password.</p>
</div>

I suspect that the JavaScript code may be incorrect. Are there any alternative methods to accomplish this task?

Answer №1

Here are a few key points to note:

  1. Make sure to assign the value returned by

    document.getElementById('hidden')
    to a variable like x

  2. Buttons do not have a submit event, consider using the click event instead

  3. Double check your element IDs - it seems like you may be confusing an ID with a class in this scenario

function checkPswd() {
  var confirmpassword = "admin";
  var password = document.getElementById("pass").value;
  if (password == confirmpassword) {
    var x = document.querySelector('.hidden');
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      alert('tryagain');
      x.style.display = "none';
    }
  };
}
.hidden {
  display: none;
}
<form method="post">
  <label for="pswd">enter password</label>
  <input type="password" id="pass">
  <input type="button" value="go" onclick="checkPswd();" /></form>
<div class="hidden">
  <p>this part I want hidden from people who don't know the password</p>
</div>

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

Using JQuery to SlideUp with a Background Color Fading Behind an Image

I'm currently utilizing JQuery slideUp/slideDown functionality to create an overlay effect on an image. This overlay is initially hidden, only appearing when the mouse hovers over the image and sliding up from the bottom. The issue I'm facing is ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...

Centering two images by stacking them with Bootstrap 5

I'm working on a bootstrap layout with two columns, and I need to achieve a semi-opaque background image that covers the entire column with a dark overlay. This is to create contrast for a logo that will be centered within the column. I've tried ...

The text does not automatically move to the next line

How can I make the content in this form section wrap to the next line in a list-item and overlap the width of the div content? The second line, particularly where it mentions Security Question two https://i.sstatic.net/5CVi2.png This is my HTML & CS ...

The table is not visible when using Bootstrap Vue

Can anyone help me with displaying a table of flowers? I am having trouble making it show up on my page. Not quite sure how to use my data to get the flowers to display properly. Any guidance or advice would be greatly appreciated. <b-table> ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Tips for concealing the edges of a scroll bar while utilizing scroll as overflow

Basically, I have a div that is positioned absolutely and has multiple children elements. This div can be scrolled horizontally to see all its content, but the scrollbar hangs off the bottom, hiding the bottom border radius. Here is the HTML code: <ul ...

What is the best way to stack text boxes vertically in CSS/HTML?

How can I arrange these textboxes so that .textbox appears at the top, followed by textbox1 below? CSS .textbox { border: 1px solid #848484; -moz-border-radius-topleft: 30px; -webkit-border-top-left-radius: 30px; border-top-left-radius: ...

Developing an npm console application that is "installable" similar to tools like yeoman, gulp, or grunt

Recently dipping my toes into the world of NPM, I've been itching to create a package that functions as a console app (think gulp and grunt). My goal is simple: I want users to be able to run npm install -g mypackage followed by mypackage This sh ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

JQuery is failing to properly return the string containing special characters like apostrophes

Storing the name "Uncle Bob's Organic" in the data-Iname attribute caused a retrieval issue, as it only retrieved up to "Uncle Bob". Here is the process used for retrieving the value from the data-Iname: var itemName = $(this).attr("data-Iname"); T ...

Stop unwanted spam submissions on my form

I am working on creating a send to a friend form that is spam-resistant. After some research, I found the following helpful sources: Preventing Email Header Injection Spoofed Form Submissions Is the code below sufficient for preventing spam? It remove ...

What is the best way to align text in the middle on smaller devices like phones and iPads?

I have been working on a login screen and encountered a problem with the layout on smaller devices. Despite centering all the content perfectly on my computer's browser, when I inspect it using developer tools for smaller devices, everything shifts to ...

Utilize Python to extract a table from an HTML document

I would like to retrieve a table from an HTML file. Below is the code-snippet I have written in order to extract the first table: import urllib2 import os import time import traceback from bs4 import BeautifulSoup #find('table',{'class&ap ...

Show the user's input on the canvas

Currently, my setup consists of 3 elements - a text field and a submit button at the top, with a canvas below them. I am looking for a way to showcase user input on the canvas after they click the submit button. If you have any JavaScript suggestions, I w ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

Using $sce in ng-repeat within Angular configuration parameters

I have been trying to incorporate videos using iframes, but no content is being displayed even with the correct embed link. Strangely, when I manually input the link into the iframe tag, the videos show up as expected. Here is the code snippet where I am f ...

Is it necessary to clear out older node.js sessions that are saved in a database?

After incorporating a database session storage for my node application, I noticed that abandoned sessions could potentially linger in the database indefinitely if a user never returns to the application or clears their cookies. Would it be advisable for m ...

Issue with ng-cloak not resolving flicker on button in Chromium; strangely, ng-cloak CSS doesn't apply as expected

Here is a snippet of my HTML code: <button type="button" class="btn btn-primary ng-cloak" ng-click="ctrl.add(ctrl.userProfile.username)" ng-hide="ctrl.userProfile.added">Add</button> The code above is a part of the larger HTML document shown ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...