What is causing this form and validation to malfunction?

I've been honing my skills in basic programming using Bootstrap, HTML, CSS, and JavaScript. Currently, I'm working on a website that begins with a landing page prompting for a password before redirecting to another page.

The issue I'm encountering is that the form and JavaScript validation are not syncing up correctly. I'm unsure of what's causing this problem or where I may be going wrong. Any assistance would be greatly appreciated! Thank you!

<div class="jumbotron">
  <form name="PasswordField" action="">
    <div class="form-group">
      <label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
      <input type="password" class="form-control" id="password" placeholder="Password">
    </div>
    <button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
  </form>
</div>

<script type="text/javascript">
  function isValid(password)
  {
    var pass ="seahorse";
    var password = document.getElementById("password");

    if (password.value.toUpperCAse().match(pass))
    {
      window.location.href = "HappyChristmas.html";

      return true;
    }
    else
    {
      alert('Nope, try again');

      return false;
    }
  }
</script>

Answer №1

  1. Make sure to call the isValid() function when submitting the form.
  2. Your code transforms the input value using toUpperCase() and then checks if it matches a password in lowercase like "seahorse".

I have created a snippet based on your code, and it seems to be working perfectly fine.

I included an onclick event on your submit button to trigger the isValid() function.

It's worth noting that you are passing a parameter to the isValid() function, but it's not necessary as you can directly access the password element and its value within the function.

Additionally, you are returning a boolean from the function, which is unnecessary since there are no conditional statements in your script. When using functions like window.location.href or alert(), the code will stop executing anyway.

function isValid()
{
    var pass = "seahorse";
    var password = document.getElementById("password");

    if (password.value.match(pass))
    {
        window.location.href = "HappyChristmas.html";
    }
    else
    {
        alert('Nope, try again');
    }
}
<div class="jumbotron">
  <form name="PasswordField" action="">
    <div class="form-group">
      <label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
            <input type="password" class="form-control" id="password" placeholder="Password">
    </div>
    <button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
  </form>
</div>

Answer №2

Start off by adding the event to the form in order to trigger your JavaScript function

<form name="PasswordField" action="/where/to/go" onsubmit="return isValid()">

Next, eliminate the argument from the function definition

function isValid(password){ ... }
as it is being replaced with the DOM node (
var password = document.getElementById("password");
)

Afterwards, modify this line of code

if (password.value.toUpperCAse().match(pass)){

to the following

if (password.value.toUpperCase() == pass.toUpperCase()){

Answer №3

In this scenario, there are two main issues that need to be addressed: 1. The isValid function is not being called from any part of the code. 2. There is no parameter named password being passed into the function.

<div class="jumbotron">
        <form name="PasswordField" action="">
          <div class="form-group">
            <label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
            <input type="password" class="form-control" id="password" placeholder="Password">
          </div>
          <-- Add an ID to the button -->
          <button type="submit" id="submitBtn" class="btn btn-default">Submit</button>
        </form>

<script type="text/javascript"
            const pass ="seahorse"
            const password = document.getElementById("password");

            const submitBtn = document.getElementById("submitBtn");
            submitBtn.addEventListener("click", e=>{
              e.preventDefault();
              isValid(password);
            })

            function isValid(passInput) {
                if (passInput.value.toLowercase().match(pass)) {
                    window.location.href = "HappyChristmas.html";
                    return true;
                } else {
                    alert('Nope, try again');
                    return false;
                }
            }
</script>

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

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Display a dialogue box when encountering a Vuetify error. Only open the dialogue box under certain conditions

I am currently implementing vuetify into my project. The main issue I am facing is related to the dialog component, which I only want to open in case of an error. The scenario involves a button calling a backend service to save a product in the database, a ...

Exploring Ways to Navigate to a Component Two Steps Back in Angular

Let's say I have three routes A->B->C. I travel from A to B and then from B to C. Now, is it possible for me to go directly from C to A? ...

What is the best method for storing a JavaScript widget with analytics - should it be done dynamically or statically?

My widget comes with a customizable boot loader that is used on websites. The boot loader file retrieves the settings for the widget and generates it accordingly. Normally, the content of the bootloader file remains static unless there are modifications ma ...

Instantly see changes without having to manually refresh the screen

I need help figuring out how to update my PHP webpage or table automatically in real-time without requiring a manual refresh. The current functionality of the page is working perfectly fine. Specifically, I want the page to instantly display any new user ...

Obtain the final value within a URL's path segment

If we have an href similar to: http://localhost:8888/#!/path/somevalue/needthis Is there a way to extract the last value in the path string (i.e., "needthis")? I experimented with window.location.pathname, but it only returns "/". Another attempt was m ...

Personalized HTML Input Field for Digital Keyboard Scores

As a new JavaScript beginner, I have experimented with various approaches in an attempt to create a website that features a digital piano experience without the actual instrument. My goal is to develop a platform where pressing multiple keys together will ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Creating a specific type of table using Ruby on Rails

Is it feasible to create a table with two columns, where the left column incorporates multiple rows with a scroll bar, and the right column contains a large box housing buttons that alter based on the selection of blocks in the left column? ...

java printwriter not cooperating with javascript

Hey there, I'm currently working on a webpage created from a servlet using PrintWriter. I'm adding HTML, CSS, and JavaScript to the page, but unfortunately, the JavaScript functions are not functioning properly. Could this be due to a syntax erro ...

Calculating and modifying a specific value in my local storage using JavaScript

I've been working on a code that allows me to add, display, and delete objects in local storage. It's functioning fine, but I'm facing an issue when trying to update a specific object. Instead of modifying just the particular object I want, ...

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

React State Displays Incorrect Value of False Instead of True

Task is quite straightforward. Once a checkbox is clicked, the itemOne state is initially set to true. Subsequently, it should switch states if clicked again. Upon invoking itemOneSelected, itemOne is displayed as false. The query: What is the reason behi ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

Having issues integrating Soundcloud iframe into Bootstrap 4

Explore the website First and foremost, I want to express my gratitude to all those who are willing to assist me! As a complete beginner, I hope my explanation will be clear enough. I am in the process of constructing a music label website using Bootstrap ...

JavaScript's inability to load images lazily poses a significant challenge

I'm having trouble implementing lazy loading for my images using JavaScript. When I change the html attribute from src to data-src, the images do not display at all. Additionally, when attempting to use an intersectionObserver to lazily load the image ...

Guide on transferring images from user interface to server

I'm struggling with saving images to my database. When the Upload Image button is clicked, a modal opens with fields for Image Title and Input File. After clicking Save, the data goes to the image.js file. Can someone please explain how to save these ...

Are there issues with the flex-grow-1 behavior in Visual Studio or possibly Razor?

I experimented with the styling below on Codeply and saw that it functions as per Bootstrap guidelines. However, after transferring this code to a Razor component in Blazor, I noticed that flex-grow-1 does not function at all. Upon checking bootstrap.min. ...