What is the process for logging in using a Bootstrap modal?

I am currently working on creating a login feature using a bootstrap modal, but unfortunately, I am facing some issues with it. If anyone is willing to offer their assistance, I would greatly appreciate it.

My knowledge of JavaScript and Bootstrap is limited.

function login(){
        
        var username=document.getElementsByName("username").value;
        var password=document.getElementsByName("password").value;
        if(username.value == null && password.value == null){
             $('.alert').show();
            
        }
         else{
       document.getElementById("wrongpassword").innerHTML="Thank u very much"; 
         }
    }
.alert{
  display:none;
}
<div class="modal fade" id="modal1"  role="dialog">
    <div class="modal-dialog">
    <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h3 class="modal-title text-center" style="color:#333366;"><strong>LOGIN TO FOOD SAVIOR</strong></h3>
        </div>
        <div class="modal-body">
<div class="form-group">
<input type="text" placeholder="Username" name="username" class="form-control" style="height:40px;" required>
</div>
<div class="form-group">
<input type="password" placeholder="Password" name="password" class="form-control" style="height:40px;" required>
</div>
<div class="text-center">
<input type="submit" value="LOGIN" name="login_btn" id="login_btn" onclick="login()" class="btn btn-primary" style="background-color:#333366;height:40px;color:#ffffff">
</div>
            
            <div class="alert alert-danger alert-dismissable fade in">
                <button type="button" class="close" data-hide="alert">&times;</button>
                    <p> You Entered Wrong Detail. Enter Again
                    </p>
            </div>
            
            <p id="wrongpassword"></p>
<h4 class="text-center"><a href="#">Forget Password</a></h4>
</div>
        <div class="modal-footer">
<h4 class="text-center">Don't have Account yet? Let's <a href="#modal2" data-toggle="modal">Sign up</a> its fun and easy!</h4>
            <div class="text-center"><button type="button" class="btn btn-success" data-dismiss="modal"><p>Close</p></button>
        </div>
        </div>
      </div>
      
    </div>
  </div>
  
  <a href="#modal1" data-toggle="modal">
            <h5>Login</h5></a>

strong text

Answer №1

When your code doesn't run as expected, there are three main reasons to consider:

  • If you are using `getElementsByName` and treating it as a single DOM element instead of a collection, make sure to add `[0]` after the function call to access the first element in the collection.

  • Be cautious of accessing the `value` property multiple times for your `username` and `password` elements. Once you've assigned the values to variables, there's no need to extract them again in your `if` statement.

  • Ensure you are checking for the right conditions when displaying an alert. Instead of comparing `username == null && password == null`, focus on `!username || !password`, as `username` and `password` are always strings and never `null`. Another approach is to check if they are empty strings with `username === '' || password === ''` or converting them to booleans for a more concise comparison.

Demo Snippet:

function login() {
  var username = document.getElementsByName("username")[0].value;
  var password = document.getElementsByName("password")[0].value;
  
  if (!username || !password) {
    $('.alert').show();
  } else {
    document.getElementById("wrongpassword").innerHTML = "Thank u very much";
  }
}
.alert { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="modal fade" id="modal1" role="dialog">
  <div class="modal-dialog">
  
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h3 class="modal-title text-center" style="color:#333366;"><strong>LOGIN TO FOOD SAVIOR</strong></h3>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <input type="text" placeholder="Username" name="username" class="form-control" style="height:40px;" required>
        </div>
        <div class="form-group">
          <input type="password" placeholder="Password" name="password" class="form-control" style="height:40px;" required>
        </div>
        <div class="text-center">
          <input type="submit" value="LOGIN" name="login_btn" id="login_btn" onclick="login()" class="btn btn-primary" style="background-color:#333366;height:40px;color:#ffffff">
        </div>

        <div class="alert alert-danger alert-dismissable fade in">
          <button type="button" class="close" data-hide="alert">&times;</button>
          <p> You Entered Wrong Detail. Enter Again
          </p>
        </div>

        <p id="wrongpassword"></p>
        <h4 class="text-center"><a href="#">Forget Password</a></h4>
      </div>
      <div class="modal-footer">
        <h4 class="text-center">Don't have Account yet? Let's <a href="#modal2" data-toggle="modal">Sign up</a> its fun and easy!</h4>
        <div class="text-center"><button type="button" class="btn btn-success" data-dismiss="modal"><p>Close</p></button>
        </div>
      </div>
    </div>

  </div>
</div>

<a href="#modal1" data-toggle="modal">
  <h5>Login</h5>
</a>

Answer №2

One potential issue is that you are trying to access the .value Property twice:

    function login(){

         var username=document.getElementsByName("username");
         var password=document.getElementsByName("password");
         if(username.value == null && password.value == null){
              $('.alert').show();

         }
         else{
       document.getElementById("wrongpassword").innerHTML="Thank u very much"; 
          }
     }

Make sure you are properly targeting the elements you want to retrieve the values from.

Answer №3

Values for username and password are already assigned as follows:

    var username=document.getElementsByName("username").value;
    var password=document.getElementsByName("password").value;

This simplifies the code to:

    if(username == "" || password == ""){

Avoid using null and compare with empty strings instead. It appears you intended to use || and not &&.

Answer №4

Using .value twice in your function is causing it to not work correctly. Please make the following changes:

function login(){

    var username=document.getElementsByName("username");
    var password=document.getElementsByName("password");
    if(username.value == null && password.value == null){
         $('.alert').css("display","block");

    }
     else{
   document.getElementById("wrongpassword").innerHTML="Thank u very much"; 
     }
}

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

Can you display a popup on a leaflet map from beyond its boundaries?

Utilizing leaflet maps, I have implemented a functionality where clicking on the map opens a popup at a specified location and centers on that position. The code for this is as follows: var popup = L.popup(); function onMapClick(e) { popup . ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

Synchronize Protractor with an Angular application embedded within an iframe on a non-Angular web platform

I'm having trouble accessing elements using methods like by.binding(). The project structure looks like this: There is a non-angular website | --> Inside an iframe | --> There is an angular app Here's a part of the code I'm ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

Progressing in a connected sequence of changes on a linear graph with distinct points and a pause

A jsfiddle has been created here. Looking to move a circle along a sine wave graph, triggered by a click event. The circle should stop at specific x and y value pairs on the graph before moving to the last point and looping back to the first (ideally unti ...

Executing a JavaScript function to interact with a nodeJS HTTP server

I'm currently setting up a basic nodeJS HTTP server. When accessing it from the browser with http://localhost:8081, everything runs smoothly. However, when I try to use a JS fetch() method, I encounter a 404 error: GET http://localhost/:8081?q=hi Ja ...

Dynamic Loading of View and Controller in Angular JS using ui-router

Is there a way to dynamically load both a view and its corresponding controller in my application? I anticipate having multiple views and controllers in my app, and I would prefer not to load all controller definitions during application setup. Instead, I ...

Extract the last word from a string, filter out any special characters, and store it in an array

Here is the content of the xmlhttp.responseText: var Text = "FS2Crew A320 Checklist_1""FS2Crew Flight Crew A320 Main Ops Manual_1""FS2Crew Flight Crew A320 Main Ops Manual_10""FS2Crew Flight Crew A320 Main Ops Manual_11&q ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

Removing a database record with JQuery

I have implemented a PHP function that converts any 2D PHP array into an HTML table. Within the table, I want to include a delete button in each row. When the user clicks on the delete button, I need jQuery to extract specific fields (3 fields) and submit ...

Ensuring the Persistence of Column State in Material-UI DataGrid/DataGridPro when Adjusting Visibility Using Column Toolbar

We have integrated MUI DataGrid into our React project. Currently, I am exploring options to save the state of columns after toggling their visibility using the DataGrid toolbar column menu. After each re-render, the column setup returns to its default st ...

How to Use PHP to Submit Form Information

I am a beginner in PHP and I need help with sending form details to an email address. I have tried looking for solutions online but I keep running into the same issue - when I submit the form, it downloads the PHP file instead of sending an email. Below i ...

Issues with navigating jQuery UI links while offline in Google abound

Hello, I am a newcomer to jQuery and I am facing an issue with my code. I added the <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> but for some reason, my jQuery is not working. I have tried searching ...

Documentation for Lambda function within an object

Looking to properly document the sock and data variables using JSDoc in my code. var exec = { /** * @param {Number} sock * @param {String} data */ 1: (sock, data) => { console.log("GG"); }, 2: (sock, data ...

Incorporate content from HTML into various sections

Is there a way to dynamically extract the h4 headers and the first sentence from each section of this HTML, and then add them to a new div? function summarize() { let headings = document.getElementsByTagName("h4"); // Get all H4 elements let newsText = do ...

External variable accessing the getjson function

I have a question about optimizing the usage of the title variable within the getJSON function. Here's a sample code snippet that I'm working with: for (var x = 0; x < temp_addresses.length; x++) { var title = temp_addresses[x].title; ...

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

Learn how to redirect pages or app folders to a subdomain using Next.js

I have been extensively searching the internet for information on this topic, but I haven't come across any relevant articles. For example, in the root of my project, there's a folder called pages with the following file structure: | 404.js ...

How can I resolve the issue of the input field added dynamically by JavaScript not appearing in the PHP $_POST variable?

I have a form nested within an HTML table. Using jQuery, I am dynamically adding input fields to the form. However, when I submit the form and check the $_POST array with var_dump(), the added fields are not showing up. Why is this happening? Below is th ...