Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly.

Below is the code snippet:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Password - form</title>
    </head>

    <body>

        <form>
            <label>Password</label>
            <input type="password" id="passid" />
            <br>
            <input type="submit" value="Sign In" />
        </form>

        <script>

            function passType() {
                var password = ["p1", "p2", "p3", "p4", "p5"];

                if (password.indexOf > -1) {
                    alert("That's great! Thank you!");
                } else {
                    alert("Wrong, try again");
                }

                if (password.indexOf > -1) {
                    alert("It's wrong, you have one more try...");
                } else {
                    alert("Get out now!");
                    window.close();
                }
            }
        passType();

    </script>
    </body>
</html>

Any guidance on how to correctly implement this?

Answer №1

Here are some key points to focus on:

  1. When selecting a specific element using the query selector, keep these in mind:
    • If you know the unique id of the element, use document.getElementById(id).
    • If you know the element's class, use
      document.getElementsByClassName(class)
      .
    • If you know the tagName of the element, use
      document.getElementsByTagName(tag)
      .
    • The simple way is to use
      document.querySelector('tag' / '.class' / '#id')
      . More information can be found here.
  2. Ensure that your function passType(), which validates the entered password against an array of defined passwords, is called after the user inputs their password and clicks the Sign In button.

    To achieve this, bind the submit event to an EventListener by using

    document.querySelector('form').addEventListener('submit', passType);

  3. To allow the user a second attempt if they enter the wrong password initially, store attempt counts in a variable. Use event.preventDefault() to prevent bubbling of the submit action button's EventListener.

By following these steps, your issue should be resolved. Below is the corrected code snippet:

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>

<body>

<form>
<label>Password</label>
<input type="password" id="passid"/>
<br>
<input type="submit" value="Sign In"/>
</form>

<script>

var attemptCount = 0;

function passType(event) {
    event.preventDefault();
    var enteredValue = document.querySelector('form').querySeletor('#passid').value;
    var password = ['p1', 'p2', 'p3', 'p4', 'p5'];

    if (password.indexOf(enteredValue) > -1) {
        alert("Welcome! Thank you!");
    }
    else {
        attemptCount++;
        alert('Incorrect, please try again');
        if (attemptCount <= 1) {
            alert("Incorrect, one more attempt allowed.");
            document.querySelector('form').querySelector('#passid').value = '';
        } else {
            alert('Access denied!');
            window.close();
        }
    }
}

document.querySelector('form').addEventListener('submit', passType);

</script>

</body>

</html>

Feel free to reach out with any questions or concerns you may have.

Answer №2

How do you use query selector to access a form?

let form = document.querySelector('form');

Next, listen for the submit event of the form.

form.addEventListener('submit', passType);

What is the process to access the input password field?

To access the password input, you will need to make modifications to your function. Firstly, add the following lines at the beginning of your "passType" function. This code snippet retrieves the user input and stores it in the variable pass.

let passwordNode = form.querySelector('#passid');//Obtain the DOM element
let pass = passwordNode.value;//Retrieve the input value

Then update if (password.indexOf > -1) to

if (password.indexOf(pass) > -1)
to validate the actual input provided.

DEMO

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Form with Password Field</title>
</head>

<body>

  <form>
    <label>Password</label>
    <input type="password" id="passid" />
    <br>
    <input type="submit" value="Sign In" />
    <!-- Both onsubmit and onclick events can be used here -->
  </form>

  <script>
    function passType() {
      let passwordNode = form.querySelector('#passid');//Accessing the DOM node
      let pass = passwordNode.value;
      var passwordList = ["p1", "p2", "p3", "p4", "p5"];

      if (passwordList.indexOf(pass) > -1) {
        alert("You have successfully logged in. Thank you!");
      } else {
        alert("Incorrect password, please try again.");
        if (passwordList.indexOf(pass) > -1) {
          alert("That's not correct, one more attempt...");
        } else {
          alert("Access denied! Closing window now.");
          window.close();
        }
      }

    }

    let form = document.querySelector('form');
    form.addEventListener('submit', passType);
  </script>

</body>

</html>

Answer №3

Are you wondering how to retrieve the input the user entered into the password field? You can achieve this by using

document.getElementById("passid").value
. An example code snippet is as follows:

if (password.indexOf(document.getElementById("passid").value) > -1) {
    alert("Awesome! Thank you!");
}

Keep in mind that invoking passType() at the start of the script will not be effective. This function will execute upon page load instead of waiting for the user to input a password. To address this, call it when the user submits the form like so:

document.querySelector("form").addEventListener("submit", passAll);

In addition, ensure that the passAll() function incorporates a call to Event.preventDefault() if an incorrect password is entered to prevent form submission. For more information on this topic, refer to

return false on addEventListener submit still submits the form?

Lastly, remember that validating passwords solely with client-side Javascript is not entirely secure. Users can potentially modify or bypass the script. It is advisable to verify passwords on the server side to prevent such overrides.

Answer №4

If you're in search of a method to manipulate the password field when a form is submitted, consider implementing something like this:

// listen for submit events on the form
document.querySelector('form').addEventListener('submit', handleFormSubmit);

// form submission handler function
function handleFormSubmit(event) {
  
  // prevent default form submission behavior
  event.preventDefault();
  event.stopPropagation();
  
  // obtain the password field from the form
  // event.target refers to the form element
  var passwordField = event.target.querySelector('#passid');
  
  // perform actions with the field or its value
  console.log(passwordField.value);
  
  return false;
}
<form>
  <label>Password</label>
  <input type="password" id="passid" />
  <input type="submit" value="Sign In" />
</form>

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

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

Is there a way to upload numerous images from my local disk onto a canvas using Fabric.js?

I'm currently working on an innovative Image Collage application using the power of HTML5 canvas and Fabric.js. One of the key features I want to implement is the ability for users to simply drag and drop files into the designated 'File Drag and ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

When the playback of an HTML5 Audio element is halted, the complete file undergoes downloading

Currently, I am facing a situation where a web page contains numerous Audio elements, some of which have very long durations, up to approximately two hours. To handle these audio tracks, they are created and controlled using the following code: var audio ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

What can be done to stop Bootstrap columns from shifting positions or stacking on top of each other unexpectedly?

I'm currently working on a testimonial section for my project. The challenge I'm facing is that the content within the 4 divs is not evenly distributed. As a result, when I try to adjust the width of the screen and expect them to align in a 2-2 f ...

Changes in browser size will not affect the height

Is there a way to smoothly change the height of the navigation bar when resizing the browser? Currently, it snaps to the new height when the width goes below or above 1000px. Any suggestions? nav.cust-navbar { -webkit-transition: height 2s; tran ...

A compilation of audio files compatible with all web browsers, no flash required

Currently in the process of developing a website dedicated to Songs, featuring playlists and mp3 files. I have come across various flash mp3 playlist players, however I am looking to avoid using flash and ensure compatibility with all browsers and smartp ...

The table's pagination displays above, thanks to Tailwindcss

I'm facing an issue where the pagination is showing up above the table, but I was expecting it to be displayed after the table. It would be ideal if the pagination appeared right after the table when adding multiple rows. Check this link for more inf ...

Modify the color of the text to be white

How can I modify the code below to change the text color to white? The original code is inspired by this question. I am unsure about how the text color was originally set to blue. .footer-background { padding-top: 20px; padding-bottom: 20px; bac ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

The iframe came to a halt as soon as it was no

I am currently developing a live video website that utilizes third-party tools to play the videos. To simplify things, I have embedded all the components required for live video into a single HTML page. Here is how it looks: <iframe data-v-140cfad2= ...

How to Disable a Button with JavaScript in a Vue.js Application Without Using jQuery

I'm currently in the process of transitioning old jQuery code to JavaScript for a Vue.js application. function DisableSubmit() { submitButton.prop('disabled', true); submitButton.attr('data-enabled-value', submitButton.val ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

CSS - Creating a Gradient Effect on div Borders for a Transparent Fade Effect across a Specified Distance

I am trying to achieve a fading effect for the background color of a div that contains a form. The solid background should fade out to transparent based on a pixel variable, allowing the background behind it to show through. This pixel value determines how ...

The Express.js feature "app.use() mandates the use of middleware functions"

Currently, I am delving into learning Express.js 4 and Node, but I seem to have hit a roadblock with an error that has me stumped. I'm attempting to utilize the node-sass package to compile my sass code; however, I've encountered obstacles in ge ...

Step-by-step guide on incorporating CSS box-shadow with the .style JavaScript property

I have a JavaScript code snippet that looks like this: document.getElementById("imgA").style.box-shadow = "0 0 5px #999999"; The hyphen in box-shadow is causing an invalid assignment exception to be thrown by the JavaScript engine (specifically in Firefo ...