Button click does not result in the modal closing

Trying to create a modal with a try-catch block that closes the modal if the form is valid and correctly filled out.

The function 'login' includes a line $('#dialog').modal('hide'); that doesn't seem to work properly.

  <script>
        function login() {

            var contact = new Contact();
            contact.name = document.getElementById('name').value;
            contact.email = document.getElementById('email').value;
            contact.zipCode = document.getElementById('plz').value;
            contact.city = document.getElementById('ort').value;
            contact.street = document.getElementById('strasse').value;

try {
    contact.validate();  
}
catch(err) {
    return window.alert(err.message);   
} 

contactStorage.newContact(contact);}
$('#dialog').modal('hide');
    </script>



    </head>

This is the modal

 <div class="container">
                <h2></h2>
                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#dialog">
                    Open Login Dialog
                </button>

                <!-- The Modal -->
                <div class="modal" id="dialog">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">Login (in header)</h4>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>

                            <div class="modal-body">
                                <div class="container">
                                    <p>In the body:</p>
                                    <form>
                                        <div class="form-group row">
                                                    <label for="name" class="col-sm-2 col-form-label">Name</label>
                                                    <div class="col-sm-10">
                                                        <input type="text" class="form-control" placeholder="Name" id="name">
                                                    </div>
                                        </div>
                                        <div class="form-group row">
                                            <label for="email" class="col-sm-2 col-form-label">E-Mail</label>
                                            <div class="col-sm-10">
                                                <input type="email" class="form-control" placeholder="E-Mail" id="email">
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label for="plz" class="col-sm-2 col-form-label">Zip Code</label>
                                            <div class="col-sm-10">
                                                <input type="number" class="form-control" placeholder="Zip Code" id="plz">
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                                <label for="city" class="col-sm-2 col-form-label">City</label>
                                                <div class="col-sm-10">
                                                    <input type="text" class="form-control" id="ort" placeholder="City">
                                                </div>
                                            </div>
                                        <div class="form-group row">
                                            <label for="street" class="col-sm-2 col-form-label">Street Address</label>
                                            <div class="col-sm-10">
                                                <input type="text" class="form-control" id="strasse" placeholder="Street Address">
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary btn-block" onclick="login()">Save</button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

Answer №1

The issue at hand is that the $("#dialog").modal('hide') code is not present inside your login function block. The corrected version should look like this:

function login() {

        var contact = new Contact();
        contact.name = document.getElementById('name').value;
        contact.email = document.getElementById('email').value;
        contact.zip = document.getElementById('plz').value;
        contact.city = document.getElementById('ort').value;
        contact.street = document.getElementById('strasse').value;

try {
    contact.validate();  
}
 catch(error) {
    return window.alert(error.message);   
} 

contactStorage.saveNewContact(contact);
$('#dialog').modal('hide');
}

Answer №2

It appears that the login function is being closed on the line before the modal is closed. To solve this issue, consider modifying the code as follows:

kontakteSpeicher.neuerKontakt(kontakt);
$('#dialog').modal('hide'); }

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

vuejs default properties initialized with vue-i18n

I am trying to establish a default property from a dictionary in this way: props: { title: { type: String, default: this.$t("basic.confirm"), }, description: { type: String, } }, ... The $t function is part of the vu ...

Having a strange glitch when creating a discord bot. Any suggestions on how to get it up and running smoothly?

Each time I attempt to launch my Discord bot, an error pops up in PowerShell. C:\Users\alexa\Desktop\WHA Period Bot\index.js:1 c SyntaxError: Invalid or unexpected token at Module._compile (internal/modules/cjs/loader.js:891: ...

Issue with Google map displaying incorrectly when attempting to print

I am experiencing an issue with printing a Google Map using the JavaScript API V3. The problem I am facing is that the map is split into two parts, with the top and bottom sections overlapping each other. Here is the code snippet: var geocoder; var ...

Warning: Knex was unable to acquire a connection due to a timeout, resulting in an UnhandledPromiseRejectionWarning

I'm having trouble connecting my Telegram bot to the database using knex. I am working with MySQL, and I have already created the database and tables which are visible on the /phpMyAdmin page. The credentials used for accessing the database in my code ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

What is the process by which nodejs interprets and analyzes c++ code?

My expertise lies in Javascript, but I'm intrigued by the connection between Node.js and C++. Despite their differences, I wonder how they interact and communicate with each other. ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

Unable to retrieve the email addresses of Facebook users using the Facebook JavaScript SDK

Utilizing the Facebook authentication feature on my website through javascript sdk, I am able to retrieve my own email and name. However, when users log in, only their names are accessible (since it's linked to my fb developer app). Despite prompting ...

Retrieve and showcase PHP results utilizing the power of jQuery/AJAX

I am working with a Leaflet map and a text input field. My goal is to extract the address from the text input, process it using a PHP script, and receive the results back via jQuery. Below is the form structure: <form id="mapcheck" method="POS ...

Easily create svg charts for use on both servers and mobile devices

Looking to create a consistent bar chart on both desktop and mobile devices using SVG. Considering using d3.js with node.js for this purpose. Willing to run node.js on the server side. How can I write JavaScript code that works on both server and client si ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Ways to enhance the performance of my websites' backend systems

Greetings! I am currently working on developing backends in ASP.NET 2.0, and have taken steps to optimize the performance by caching images, GZIPing CSS and JS files. The load speed of each option is good, but I am eager for even faster loading times. Alt ...

javascript The event handler is not functioning properly for the dynamically loaded AJAX content

I am facing an issue with adding a JavaScript event listener to a dynamically loaded div via AJAX. Below is my code snippet: var QuantityMiniCart = function() { var infor = document.querySelectorAll( '.mini-cart-product-infor' ); if ( ...

Low frame rate in a straightforward Three.js environment on Safari for MacOS

I have created a demo that runs smoothly on Chrome and Firefox but lags terribly on Safari. Disabling antialiasing slightly improves the FPS, but not significantly. I am wondering if there are ways to optimize my code, perhaps by implementing caching techn ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Which is more effective for a webpage that solely calculates a formula: user input fields in DIVs or forms?

My idea is to create a webpage with initially 6 input fields, which can expand to 7, 8, 9, or 10 fields when a button is pressed. These fields will have editable preset values that will be used to calculate a final value using a formula. Should I use f ...

Guide on interpreting unordered lists and returning the outcome to Java

The xhtml-file provided below showcases a structure for content creation: <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" temp ...

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...