Trigger submission issue encountered with Jquery in a dialog (modal) window

It's somewhat difficult for me to fully explain my problem. Nevertheless, I'll give it a go.

In my HTML code, I have implemented several triggers using Jquery. Trigger 1 is responsible for validating specific items within a form. Once Trigger 1 completes its validation, Trigger 2 is triggered.

Here's what's happening: when the code below is encountered - if ($(".Reason").val() == 4) { - a Dialog window appears with two options: yes or no. If "yes" is selected, Trigger 2 (submit) is called; otherwise, the Dialog window closes for corrections...

If the specified condition is not met, Trigger 2 (submit) processes correctly and submits the form. However, it seems that there is a "return false" statement preventing the execution of Trigger 2 if the condition is met.

Some of the lines in the code may be irrelevant, but I've left them in there. If the consensus is to remove them, I will do so.

I apologize for the extensive amount of code.

Hopefully, someone can provide assistance!

$(".validateForm").click(function () {

        if ($(".Reason").val() == 4) {
            //bankingModal
            ExpectedAmount = $(".CloseAmount").val();  
            cashTotal = parseInt($(".cashtotal").val());                  
            chequeTotal = parseInt($(".chequeTotal").val());         

            formTotal = cashTotal + chequeTotal;
            formTotal = parseFloat(formTotal).toFixed(2);

            if (formTotal !== ExpectedAmount ) {
                $(".bankModal").dialog({
                    resizable: false,
                    height: 210,
                    width: 400,
                    modal: true,
                    position: 'center',
                    buttons: {
                        'Yes - Submit': function () {
                             $('.submit').click()
                            $(this).dialog("close");

                        },
                        'No - Cancel': function () {
                            $(this).dialog("close");
                        }
                    }
                })
            }
        } else {
            //submitBanking();
            $('.submit').click()
        }
        return false;
})

// The following is the second trigger.

$('.submit').click(function () {

// Unset error

        formErr = false;
        window.onbeforeunload = null;

        // Validation for Change Request
        if ($(".outgoing").length > 0) {
            if (validateChangeRequest()) {
                formErr = true;
            }
        }

        // If text box is empty change values to 0.00
        $('.cashSum', '.cashSumOut').each(function () {
            if (!$(this).val()) {
                $(this).val('0.00');
            }

        });

        // Check if numeric values are ok prior to submit.
        $(".cashAmount").each(function () {
            if (isNaN($(this).val())) {
                modal("", "Only numbers are permitted");
                formErr = true;
            }
            if (checkNegatives($(this))) {
                modal($(this), "Negative values are not permitted");
                formErr = true;
            }
        });
        if (formErr) {
            return false;
        }
        if ($("#cashCheque").length != 0) {          
            return false;
        }
    });

Answer №1

Why do you repeatedly create the dialog every time the condition is met?

Instead, create it once in the DOM ready handler and only open the dialog when the condition is satisfied.

$(".validateForm").click(function() {

    if ($(".Reason").val() == 4) {
        //bankingModal
        ExpectedAmount = $(".CloseAmount").val();
        cashTotal = parseInt($(".cashtotal").val());
        chequeTotal = parseInt($(".chequeTotal").val());

        formTotal = cashTotal + chequeTotal;
        formTotal = parseFloat(formTotal).toFixed(2);

        if (formTotal !== ExpectedAmount) {
            $(".bankModal").dialog('open');
        }
    } else {
        //submitBanking();
        $('.submit').click()
    }
    return false;
});

$(".bankModal").dialog({
    resizable: false,
    height: 210,
    width: 400,
    modal: true,
    position: 'center',
    autoOpen : false,
    buttons: {
        'Yes - Submit': function() {
            $('.submit').click()
            $(this).dialog("close");

        },
        'No - Cancel': function() {
            $(this).dialog("close");
        }
    }
});​

UPDATE

The form should be submitted only when there are no errors.

if (formErr) {
    return false;
}
if ($("#cashCheque").length != 0) {          
    return false;
}

$('form').submit(); // submit when no errors

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

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...

Tips for automatically focusing a div upon page load

Here is a code snippet for you to review: <div id="details"> <nav> <a href="#1"><span>Summary</span></a> <a href="#2"><span>Perso ...

Incorporating a URL into an HTML marquee

As a beginner in coding, I'm currently exploring how to incorporate a link into my marquee. My goal is to eliminate any color change or underline animation as well. Do you have any recommendations? .Marquee { color: #da6fe2; background-color: t ...

Sorting of tables does not function properly following an ajax request

I built a table that utilizes an AJAX response triggered by selecting a date from a drop-down menu. <!--datepicker--> <div class="col-md-4"> <input type="text" name="date_po_month_picker" id="date_po_month_picker" class ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...

Setting the appropriate width for the main div element using CSS

Imagine wanting to craft an HTML page featuring a primary div housing all of the content. In this scenario, the div should enclose other divs and remain centrally fixed on the page, similar to the image provided. How should one determine the appropriate w ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Executing an AJAX request on Rails 3 without triggering a redirect by using a link/button

What is the most effective method for executing an ajax command using a link in Rails 3.1 with jQuery? Currently, I am attempting to use a link to trigger code from the "update_me" controller action. The line in views/products/new.html.erb looks like this ...

Troubleshooting common issues with PHP's simple HTML DOM parser

I've encountered an issue while working on a scraper for a website that involves crawling through links. The error message I'm receiving is as follows: PHP Fatal error: Uncaught Error: Call to a member function find() on null in D:\Projekti ...

Is it possible to enclose an image with two <div> tags in a single line?

Can anyone help me with this layout issue I am facing? I have two <div>s wrapping an image in the same row, but for some reason, the right <div> keeps dropping below. I've attempted using float, display:inline-block, and tweaking the styl ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

PHP Administrator Access

When a user logs in as an admin on my website, I want certain options to be available. My concern is ensuring the security of this admin account. Currently, after the login process is authenticated, I set $_SESSION['status'] = 'authorized&ap ...

Sort out the table using Javascript and then choose all the checkboxes

I'm struggling with a function in Javascript that will only check checkboxes on visible rows of an HTML table. The table has a checkbox on each row and is filtered based on a textbox above the table. The checkboxes in the table are named chkbuild, an ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

What's the reason behind this file not opening?

When I try to insert this code into files index.html, style.css, and app.js, the page refuses to open. The browser constantly displays a message saying "The webpage was reloaded because a problem occurred." I am using a MacBook Air with macOS Big Sur and a ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...