Why isn't preventDefault() effective in this particular situation?

When attempting to obtain an OTP, the event.preventDefault() function is functioning properly. However, after updating the register-form for OTP verification, the event.preventDefault() function ceases to work.

How could this happen? Your assistance is greatly appreciated! Thank you in advance!!!

Essentially, my goal is to have a form initially containing an input field and a "Get OTP" button. Upon clicking the Get OTP button with a valid 10-digit number, I want to transition to another form where OTP verification takes place. This second form includes an input field for entering OTP and a "Verify OTP" button. The script should compare the entered OTP with a hardcoded value of 4444. However, the jQuery function preventDefault() fails in this context, redirecting me to a POST request route instead.

            $(document).ready(() => {
                //get otp form
                $('#get-otp').submit(e => {
                    e.preventDefault();
                    let number = e.target.elements.number.value;
                    number = number.trim();
                    if (number.length !== 10) {
                        $('#msg').text("Please enter a valid 10-digit number.");
                        $('.alert').css('display', 'block');
                        setTimeout(() => {
                            $('.alert').css('display', 'none');
                        }, 3000);
                    } else {
                        $('#msg').text("Please enter the valid OTP below.");
                        $('.register-form').html(`<form action="" id="verify-otp" method="post">
                            <div class="col col-sm-12 input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fa fa-keyboard-o icon"></i></span>
                                </div>
                                <input type="number" name="otp" id="otp" class="form-control" placeholder="Enter OTP here" />
                            </div>
                            <div class="checkbox" >
                                <label><input type="checkbox" />
                                    <a class="terms" data-toggle="modal" data-target="#terms_conditions-modal">
                                         <span>Agree to terms & conditions</span>
                                    </a>
                                </label>
                            </div>
                            <div class="btn-req-otp">
                                <button type="submit"
                                    style="background-color: #002e6e; color: white;" onclick="function verifyOtp()" class="btn">Verify OTP</button>
                            </div>
                        </form>`);
                        $('.alert').css('display', 'block');
                        setTimeout(() => {
                            $('.alert').css('display', 'none');
                        }, 3000);
                    }
                });
               // verify otp form
                $('#verify-otp').submit(e => {
                    e.preventDefault();
                    alert("ooo");
                    let otp = e.target.elements.otp.value;
                    otp = number.trim();
                    if (otp === 4444) {
                        $('#msg').text("Please enter a valid 4-digit OTP.");
                        $('.alert').css('display', 'block');
                        setTimeout(() => {
                            $('.alert').css('display', 'none');
                        }, 3000);
                    } else {
                        $('input[type="checkbox"]').click(function () {
                            if ($(this).prop("checked") == true) {
                                alert("Successfully registered!!!!!!");
                            }
                            else if ($(this).prop("checked") == false) {
                                $('#msg').text("Please Accept our Terms & Conditions.");
                                $('.alert').css('display', 'block');
                                setTimeout(() => {
                                    $('.alert').css('display', 'none');
                                }, 3000);
                            }
                        });
                    }
                });
            });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
    <div class="container">

        <div class="col col-lg-6 col-md-8 col-sm-12 offset-lg-3 offset-md-2 box">
            <div class="alert alert-danger alert-dismissible fade show"
                style="padding: 2px; text-align: center; display: none;" role="alert">
                <span id="msg"></span>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close" style="padding: inherit;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="register-box">
                <div class="row register-welcome">
                    <!-- dynamically change -->
                    <h2 class="text-center">Welcome to Serv Udyam...</h2>
                    <h4>A smart search for your smart home</h4>
                </div>
                <div class="row register-form">

                    <form action="" id="get-otp" method="post">
                        <div class="col col-sm-12 input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fa fa-mobile icon"></i></span>
                            </div>
                            <select>
                                <option>+91</option>
                            </select>
                            <input type="number" name="number" id="number" class="form-control"
                                placeholder="Enter Mobile No." autocomplete="off" />
                        </div>
                        <div class="btn-req-otp">
                            <button type="submit" style="background-color: #002e6e; color: white;" class="btn">Get
                                OTP</button>
                        </div>
                    </form>

                </div>
                <div class="row vendor-link">
                    <div>
                        <h6>Are you a vendor instead?</h6>
                        <a style="display: block; text-align: center;" href="#">Click Here</a>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <!-- Terms Conditions modal -->
    <div class="modal" tabindex="-1" id="terms_conditions-modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Terms and Conditions</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>1.Lorem ipsum, dolor sit amet consectetur adipisicing elit.
                        Dolor in impedit debitis ipsa quidem. Facilis velit consectetur quos ut sit?</p>
                    <p>2.Lorem ipsum, dolor sit amet consectetur adipisicing elit.
                        Dolor in impedit debitis ipsa quidem. Facilis velit consectetur quos ut sit?</p>
                </div>

            </div>
        </div>
    </div>
        <footer class="footer">© 2020 Serv Udyam</footer>
    </body>

Answer №1

The #verify-otp event must be defined before being inserted into the document.

Consider using Event Delegate, for example:

$('.register-form').on("click", "#verify-otp", function(e) {
    e.preventDefault();

This approach should be effective.

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

display the text content of the chosen option on various div elements

I created a subscription form that includes a category dropdown select field. The selected option's text value needs to appear 4 times within the form. It's all part of a single form. <select name="catid" onchange="copy()" id="catid" class="i ...

The Angular 4 application encountered a TypeError due to being unable to access the 'setupScene' property of an undefined object

How can I execute an Angular class function within the Load function in TypeScript? I am encountering an error when trying to call a method within the load method in Angular CLI, resulting in an undefined function error. import { Component, OnInit ,Elemen ...

JavaScript array contains duplicate values

I have developed a custom Asp.Net user control. To keep things simple, I have omitted some of the HTML code. <asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period"> <div ID="InputWrapperMonth" runat="server" c ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

$watch does not work properly when used with arrays

Observing an array for changes and calling a function when it does: $scope.$watch( $scope.aQuestions, function checkQuestionCount(newValue, oldValue) { debugger; if (newValue === oldValue) { ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

AngularJS mobile navigation menu toggle not functioning properly with the close feature

I am currently developing a simple Single Page Application (SPA) using an HTML template. The template includes a mobile navigation menu, but I am facing issues with it not closing when navigating through routes in AngularJS. Can anyone provide guidance on ...

Arrange JSON information in an HTML table with distinct header rows for every data category

I have a JSON object with a key:value pair named callRoot. Some examples of values for this pair are @S, @C, and @W. There are multiple objects that share the same value and I want to create an HTML table head row at the beginning of each group and repeat ...

With each click of the refresh button, a new email is dispatched

I'm struggling with my code as I try to create a contact form. My knowledge of php is limited, and I keep encountering issues. Every time I refresh the page, an email is sent automatically and I receive the "Confirm form resubmission" message which is ...

Unable to submit form upon clicking radio button in .NET Core

Trying to submit a form by clicking on a radio button. The JQuery code used for submitting the form: Form: @for (var item = 0; item < Model.Count(); item++) { <form id="myform" action="xx" controller="xxx" method="post"> ...

What could be the reason behind the vanishing border of a cell in a Bootstrap4 table when I apply a rowspan to a column?

Here is the code snippet I am working with: <table width="100%" class="table-bordered"> <tbody> <tr> <td class="font-weight-bold text-center px-1"> ...

What is the process of incorporating a Map feature (Google or Bing) into a Windows platform using PhoneGap?

I successfully completed my Phonegap app for iOS and Android, but now I am facing a nightmare with the Windows platform. I need to integrate a map in my app. For iOS and Android, I used mapsplugin, but unfortunately it does not support the Windows platfor ...

Issue with React Testing Library: Attempting to access the 'contents' property of an undefined value in Redux

Hello, I'm new to writing test cases using React Testing Library. Below is the code of my component: import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; ...

Tips for transforming a nested object into an array using JavaScript

I have a complex array containing multiple objects, each with two or more sub-objects. I am looking to consolidate all sub-objects into a single array of data using JavaScript. How can I achieve this? var array1 = [ { "dfgasg24":{ name:"a", ...

What are the steps to resolve the error "TypeError: req.next is not a function"?

I've been working on a project and keep encountering this persistent error that I can't seem to fix. I understand the issue, but unfortunately, I'm at a loss as to how to resolve it. Here is the error message: events.js:292 throw er; ...

Preset for Typescript in Babel 6

Can anyone help me find a Babel preset for Typescript that is compatible with Babel 6, rather than Babel 7? I've been searching for this module with no luck. Is it possible that the TS preset is not supported for Babel 6? ...

Place CSS elements in relation to the underlying element

This is an example of my HTML structure: <nav id="menu"> <ul> <li><a href="">Products</a></li> <li><a href="">Offers</a></li> <li><a href="">References</a>& ...

Overflowing content in a table within a div element

Issue: I am encountering a problem with resizing a table inside a div that contains input elements. When I adjust the browser window size or change to a lower resolution, the div element resizes and scales down, causing a horizontal scroll bar to appear. H ...

What is the best way to display the text of a button once it has been clicked?

Trying to implement a fade-in effect on text when clicking a button. Any assistance would be greatly appreciated! $(".btnClick").click(function(event) { var x = $(this).text(); if (x == "PowerApps") { $(this).parent(".show-details").find('. ...

Preventing Unwanted Scroll with jQuery

I'm currently working on a project where I have several description blocks that are meant to fade in when the corresponding image is clicked. The fading effect works fine, but there's an issue with the page scrolling up each time a new image is c ...