Prevent the bootstrap dropdown menu from closing when encountering a login error during form validation using ajax and codeigniter

I encountered an issue with my dropdown menu login that utilizes bootstrap ajax and codeigniter. When I attempt to submit the form and there is an error, I have to click multiple times before the error message appears because the dropdown menu keeps closing upon submission.

Question: How can I prevent the bootstrap dropdown from closing when submitting my form on the dropdown menu login, so that the error message displays after the first click?

In attempting to address this issue in the response.success false section, I tried the following:

$('#dropdown-login').on('hide.bs.dropdown', function () {
    $('#error').html(response.messages);
    return false;
}); 

This view is appended to the menu displayed in the code snippet at the bottom.

<li>
<div class="row">
<div class="col-md-12">
<div id="error"></div>
<form class="form" role="form" method="post"  accept-charset="UTF-8" id="login-nav">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-success btn-block">Sign in</button>
</div>
</form>
</div>
</div>
</li>

<script type="text/javascript">
$(document).ready(function() {
    $('#submit').on('click', function(e) {   
        $.ajax({
            url: "<?php echo base_url('catalog/members/login/validate');?>",
            type: 'post',
            dataType: 'json',
            data: {
                username: $('#username').val(),
                password: $('#password').val()
            },
            success: function(response){
                if (response.success == true) {

                } else {

                    $('#dropdown-login').on('hide.bs.dropdown', function () {
                        $('#error').html(response.messages);
                        return false;
                    });      

                }
            }  
        });
    }); 
});
</script>

Image

https://i.stack.imgur.com/tfAq7.png

Menu

<nav class="navbar navbar-default">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand</a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">    
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">Sign Up</a></li>
                <li class="dropdown" id="dropdown-login">
                    <a class="dropdown-toggle" data-toggle="dropdown">Sign in <b class="caret"></b></a>
                </li>
            </ul>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>
<script type="text/javascript">
$(document).ready(function() {
    $('#dropdown-login').on('click', function() {

        $('#ul-dropdown-login').remove();

        $.ajax({
            url: "<?php echo base_url();?>catalog/members/login",
            dataType: 'html',
            success: function(html) {
                $('#dropdown-login').append('<ul class="dropdown-menu" id="ul-dropdown-login" style="padding: 15px;min-width: 250px;" >' + html + '</ul>');
            }
        });
    }); 
});        
</script>

Answer №1

After some investigation, I discovered that the solution to my menu script issue was quite simple - I just needed to remove a specific piece of code.

$('#ul-dropdown-login').remove();

Here is a snippet of the menu script:

<script type="text/javascript>
$(document).ready(function() {

    $('#login-toggle').on('click', function(e) {

        //e.preventDefault();

        //$('.error').remove();

        $.ajax({
            url: "<?php echo base_url();?>catalog/members/login",
            dataType: 'html',
            success: function(html) {
                if($('#login-dropdown').length == 0) {
                $('#login-toggle').append('<ul class="dropdown-menu" id="login-dropdown" style="padding: 15px;min-width: 250px;" >' + html + '</ul>');

                }
            }
        });
    }); 


});        
</script>

And here is a snippet of the login script:

<script type="text/javascript>
$(document).ready(function() {
    $('#login-submit').on('click', function(e) {
        e.preventDefault();
        $.ajax({
            url: "<?php echo base_url('catalog/members/login/validate');?>",
            type: 'post',
            dataType: 'json',
            data: {
                username: $('#username').val(),
                password: $('#password').val()
            },
            success: function(response){
                if (response.success == true) {

                } else {

                    if($('.error').length == 0) {
                        $('#input-username').after(response.error_username);
                        $('#input-password').after(response.error_password);
                    }
                }
            }  
        });
    });      
});   
</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

Guide to embed a Google Sheets chart into a WordPress website

I'm looking to include a chart in a wordpress post, using the script generated from google sheets' publish function. When I add the script to a generic HTML page, the chart displays properly. However, when I insert it into a wordpress post, I en ...

Manipulating data rows in a table using jquery

I have a button called #add that, when clicked, adds a new row to a table. The last cell of the newly inserted row contains a delete icon that, when clicked, should remove the entire row. I thought I had everything set up correctly, but for some reason, c ...

Could it be that v-show does not function properly on elements that are not dynamic

I'm not experienced in web development and this is my first attempt at using a web framework. The framework I am currently learning is vue.js version 3. My goal: I want to create 4 app instances (nav, defaultApp, bootstrapApp, vueApp). When I select ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

Issue with two Ajax forms

Having some trouble with my ajax forms and can't seem to figure out the issue. Essentially, I have two contact forms on the same page that use the same code, with the only difference being their placement - one at the top and one at the bottom. The p ...

What is the best way to fetch images from a JSON object in a React application?

I have been trying to load images from an array of objects in React, but I keep encountering a "module not found" error. This issue has been frustrating me for the past couple of days. Can someone please help me troubleshoot this problem or provide some su ...

Encountering issues with JSON.Parse in JavaScript leads to errors

I'm encountering issues with JSON parsing in my code and I can't figure out the cause of it. I have a function that calls two ajax functions, one at the start and another in the success function. Everything seems to be working fine until I try to ...

The ng-repeat ng-switch combination is not functioning as expected

My data can be simplified to the following in my code: function DemoCtrl($scope) { $scope.myData= [ {text: "blah", other: 3, V: 'caseOne'}, {text: "blah", other: 3, V: 'caseTwo'}, {text: "blah", other: 3, V ...

Encountering an unidentified entity within a ReactJS application

Within a container, I've included a search bar inside a form element with two inputs - from and to, along with a submit button. Upon submitting the form, I create an OBJECT named query which looks like this: const query = { from : this.s ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...

Facing issues with building Angular 7 and Ionic 4 - getting error message "TypeError: Cannot read properties of undefined (reading 'kind')"

I need assistance with a problem I am encountering while building my Angular 7 & Ionic 4 application... When I run the ng build --prod command, I encounter the following error: ERROR in ./node_modules/ionic4-auto-complete/fesm5/ionic4-auto-complete.js ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

Having trouble sending form data through AJAX with Fancybox

One of the challenges I'm facing is using Fancybox to trigger a contact form popup when a link is clicked. The issue arises when I try to POST the form data to a PHP file, send an email, and display a success message. Interestingly, upon submitting t ...

Backstretch malfunctioning

Looking to enhance my webpage with a backstretch image slideshow effect using the body background, but encountering issues. The code I have included before the </head> tag is: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery ...

Blocking negative values when a button is clicked in Vue.js using v-on:click

How can I prevent the counter from going below 0 when clicked in this Vue component? Do I need to create a separate method to block it? Thank you for your assistance. <button v-on:click="counter.document -= 1">-</button> <h3>{{coun ...

Is there a way to invoke a function in an iframe from its parent?

How can I call a function that is in an iframe from the parent document? If the function were in the parent, I could simply use parent.func(); but since it's within the iframe, how can I still call it successfully? JavaScript keeps saying it can' ...

Entering a value into an HTML textbox using Awesomium in VB.NET

This code snippet is used to split text from a listbox: For Each Item As Object In ListBox1.SelectedItems TextBox2.AppendText(Item.ToString + Environment.NewLine) Next Dim str As String = TextBox2.Text D ...