Home > Software design >  Show Pop up message after form validation in javascript
Show Pop up message after form validation in javascript

Time:10-03

I am new in javascript and currently I am creating an enrolment form where it will validate the cellphone where it only accepts 11 characters and numbers. the only problem is that everytime I click on submit, instead of the message popping up, it completely refreshes my tab. Is there any way to fix this?

Form Code:

<!doctype html>
<html lang="en">
  <head>
        <nav >
            <a  href="Homepage.html"><img src="USTLogo.png" width="30" height="30" alt="">School</a>
            <button  type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
              <span ></span>
            </button>
            <div  id="navbarNav">
              <ul >
                <li >
                  <a  href="Homepage.html">HOME<span >(current)</span></a>
                </li>
              </ul>
            </div>
          </nav>
    <title>Enrollment Form</title>

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

    <!-- Bootstrap CSS -->

    <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">
    
    <!-- CSS -->
    <link href = "design.css" rel = "stylesheet" type="text/css"/>

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

    <h1 >Enrollment Form</h1>

    <div >
        <div >
            <!-- empty space on the left side --> 
            <div ></div>

             <!-- Main Content --> 
            <div >
                <div id ="ui">
                    <form id = "form" >

                        <div >
                            <div >
                                <label >Cellphone Number</label>
                                <input id = "Cp_Number" type="text"  placeholder="Enter Cellphone Number..." required>
                            </div>

                            <div >
                                <label >Age</label>
                                <input  id = "Age" type="text"  placeholder="Enter your age..." required>
                            </div>
                      
                        <br>
                        <div >
                        <div >
                            <button type="submit" >Submit</button>
                        </div>
                        <div >
                            <a href="Homepage.html" id="cancel" name="cancel"  onclick="return confirm('Are you sure you want to cancel the Enrollment?')">Cancel</a>
                        </div>
                    </div >
                    </form>
                </div>
            </div>
       <!-- empty space on the right side --> 
            <div ></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: I will be removing most of the content in the form and will only include the fields where it needs validation JS code:

const Cp_num = documet.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();
    }
  
})

CodePudding user response:

Stop using your custom javascript in the head tag. Because, of this the scripts loads before the contents and doesn't find the form element in the DOM before initialization. So, use any custom javascript inside the body tag and below all the html elements. But remember to include any other dependencies before your custom scripts. Hope it solves the problem.

CodePudding user response:

What's happening here is that your script tag is in your head:

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

And for that reason, your HTML hasn't been loaded completely, so a "form" element with the id of "form" does not exist, thus, you get an error (check your console in your browser).

This is why your e.preventDefault() method doesn't work. Because again, your HTML hasn't been loaded yet.

You have two options:

  1. Put the script tag at the bottom of your body:

Very self-explanatory, put the script tag at the end of your body, so your whole HTML loads first, and then your JavaScript file.

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

I won't explain what the defer does in depth here, but if you want some quick answer, it basically waits for your HTML to fully load before using any of the JavaScript code.

So you can try this:

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

(By the way, this method does not require you to move the script tag out of your HTML head)

You can learn more about defer here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer

(EDIT): By further inspection of the code, I found that you were using the "type" parameter in your script tag. You don't need this, and this is causing you the problem of your script tag not being used:

So from:

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

do:

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

(Another gotcha) You have a typo on the first "document" that you were selecting:

const Cp_num = documet.getElementById('Cp_Number')

"documet" is not defined, you have to change it to:

const Cp_num = document.getElementById('Cp_Number')
  • Related