Display a pop-up alert following the completion of form validation using JavaScript

I am currently learning JavaScript and working on an enrollment form that requires validating a cellphone number with 11 characters. The issue I'm facing is that every time I hit submit, the page refreshes instead of displaying the validation message. Any suggestions on how to fix this?

Form Code:

<!doctype html>
<html lang="en">
  <head>
        <title>Enrollment Form</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
    <link href = "design.css" rel = "stylesheet" type="text/css"/>

    <script src="JAVASCRIPT.js" type="text/jsx"></script>
</head>
  <body>

    <h1 class="display-1">Enrollment Form</h1>

    <div class="container">
        <div class="row">
            <div class="col-lg-3"></div>

            <div class="col-lg-6">
                <div id ="ui">
                    <form id = "form" class="form-group">

                        <div class="row">
                            <div class="col-lg-8">
                                <label >Cellphone Number</label>
                                <input id = "Cp_Number" type="text" class="form-control" placeholder="Enter Cellphone Number..." required>
                            </div>

                            <div class="col-lg-4">
                                <label >Age</label>
                                <input  id = "Age" type="text" class="form-control" placeholder="Enter your age..." required>
                            </div>
                      
                        <br>
                        <div class="row">
                        <div class="col-lg-6">
                            <button type="submit" class="btn btn-primary btn-block">Submit</button>
                        </div>
                        <div class="col-lg-6">
                            <a href="Homepage.html" id="cancel" name="cancel" class="btn btn-primary btn-block" onclick="return confirm('Are you sure you want to cancel the Enrollment?')">Cancel</a>
                        </div>
                    </div >
                    </form>
                </div>
            </div>
      
            <div class="col-lg-3"></div>
        </div>
        
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>

Note: Only essential fields for validation will be included in the form.

JS code:

const Cp_num = document.getElementById('Cp_Number')
const age = document.getElementById('Age')
const form = document.getElementById('form')
form.addEventListener('submit', (e) =>{
    var isValid = true;

    e.preventDefault();

    if(isNaN(Cp_num) || Cp_num.value == null || Cp_num.value == ''){
        alert ("Your Cellphone number is invalid!")
        isValid === false;
    }
    if (Cp_num >=12){
        alert ("Your Cellphone number is invalid!")
        isValid === false;
    }

    if(isNaN(age) || age.value == null || age.value == ''){
        alert ("Your Age is invalid!")
        isValid === false;
    }

    if (isValid === true){
        popUp();
    }
  
})

Answer №1

Avoid placing your personalized JavaScript code in the head section of your webpage. This causes the scripts to load before the content, leading to issues finding form elements in the Document Object Model (DOM) during initialization. Instead, place any custom JavaScript within the body tag and after all HTML elements. Ensure that any dependencies are included before your custom scripts. This adjustment should help resolve the issue at hand.

Answer №2

Here's what's going on: the script tag is currently in your head section of the HTML:

<script src="JAVASCRIPT.js" type="text/jsx"></script>

Due to this placement, the HTML hasn't fully loaded yet, so the form element with the id "form" doesn't exist, resulting in an error message (check your browser console).

As a result, the e.preventDefault() method is not functioning correctly because the HTML isn't fully loaded.

You have two options to address this issue:

  1. Move the script tag to the bottom of the body:

This simple solution entails placing the script tag at the end of the body to ensure that the entire HTML document loads before the JavaScript file runs.

  1. Use the "defer" attribute in your script tag:

The defer attribute essentially waits for the HTML content to load completely before executing any JavaScript code.

Try implementing the following approach:

<script src="JAVASCRIPT.js" type="text/jsx" defer></script>

(Note: Using defer eliminates the need to move the script tag out of the head section)

For more information on defer, visit: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer

(EDIT): Upon further examination, I noticed that you were including the unnecessary "type" parameter in your script tag, which is causing issues:

Instead of:

<script src="JAVASCRIPT.js" type="text/jsx"></script>

Update it to:

<script src="JAVASCRIPT.js" defer></script>

(Another point to note) There is a typo in the selection of the first "document" object:

const Cp_num = documet.getElementById('Cp_Number')

"documet" is undefined, so make sure to correct it to:

const Cp_num = document.getElementById('Cp_Number')

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

Converting a ReadStream to a ReadableStream in NodeJS: A Step-by-Step Guide

This question poses the opposite scenario to converting a ReadableStream into a ReadStream. ReadStream is a data structure utilized in Node.js ReadableStream is a structure that comes from the web platform, as detailed here As new runtimes like Deno or t ...

How to create a see-through background using three.js

I am new to working with three.js and recently came across a codepen that caught my attention. However, I am facing difficulties while trying to change the background color. After exploring various questions related to this issue, I attempted to add { alp ...

Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter" ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

Issues have been encountered with activating checkboxes on Internet Explorer while utilizing ASP.NET CheckBox controls

I'm facing an issue with an HTML form that includes two disabled checkboxes and an image with an onclick event intended to display a popup and enable the checkboxes: <input id="chk1" type="checkbox" disabled="disabled" /> <input id="chk2" ty ...

Is there a way to detect duplicate usernames in a form without actually submitting the form, and then automatically focus on the username field if a duplicate is

I need help with a user registration form that I am creating. I want the form to automatically search for an existing username as soon as the user starts typing in the username field. If the username already exists, I want the field to receive focus. In my ...

The component is no longer able to locate the imported element when it is being shared

Recently, I imported a component into the shared module in order to use it across 2 different modules. However, upon recompiling the app, an error message appeared stating that the jodit-editor, which is utilized by the shared component, is not recognized ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...

Using Hapi & Async for your API - How can you clear an array or execute a function immediately after sending a "reply" or at every new "get" request?

In the midst of developing a small API that retrieves data, performs tasks on it asynchronously, stores some of this data in an array using push, and then presents it to a client through Hapi's reply(). My goal is to clear out the array (e.g., using ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Transferring an array between Javascript and Django

I am working with an array of objects in JavaScript, like this: Arr = [0: {k;v}, 1: {k,v}] and so on, each containing numerous fields. The challenge I'm facing is in sending these objects to Django. I have attempted using JSON.stringify to send the ...

Tips for improving the loading speed of a table during scrolling with JavaScript

Is there a way to speed up the loading time of a <table> with 20000 rows? As I scroll through the page, it feels very sluggish and takes around 4-5 seconds to load the remaining table data. I'm unsure how to tackle this issue, which is why I h ...

Difficulties with choosing predecessors

Is there a way in the HTML snippet below to extract the checkall from the thing? .. <input type="checkbox" class="checkall"><label>Check all</label> <ul> <li><input type="checkbox" class="thing"><label>Thing 1 ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

Display content in the View in ASP.NET based on the parameters passed into the ActionResult function

I'm grappling with a theoretical scenario involving rendering a single View with different content based on user input using MVC in the .NET framework. Essentially, I'm looking to have just one page titled "Create Template", but its contents sho ...

Don't pay attention to the parent form tag in Bootstrap

Here is the code snippet I am working with: <div class="row"> <form id="update"> <div class="col-md-6"> <h1>Title</h1> </div> </form> <form id="insert"> <div class="col-md-6"> &l ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

Although JavaScript Handlebars does not show any errors, it fails to function properly

I've been attempting to update text on my page using handlebars, but unfortunately, it's not functioning correctly and there are no error messages being displayed. The code below is triggered once the user clicks the submit button <button ty ...