What could be causing my form to not display a validation error?

I'm currently working on a task where I need to validate a form and display a message that says 'Please complete the form!' Everything seems to be functioning correctly except for the message. What could I be missing here? How can I make this work or is there something simple that I am overlooking? I've experimented with placing the script at the top and bottom, but prefer it at the bottom to ensure the page loads quickly without any interruptions from JavaScript.

<!DOCTYPE html>
<html lang="en>
<head>
    <meta charset="utf-8">
    <title>Index</title>
    <!--[if IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <link rel="stylesheet" href="styles.css">

</head>
<body>

<form action="login.php" method="post" id="loginForm">
    <fieldset>
        <legend>Login</legend>
        <div><label for="email">Email Address</label>
            <input type="email" name="email" id="email" required></div>

        <div><label for="password">Password</label>
            <input type="password" name="password" id="password" required></div>

        <div><label for="submit"></label><input type="submit" value="Login &rarr;" id="submit"></div>
    </fieldset>
</form>

<script src="login.js"></script>


</body>
</html>

JavaScript code:

function validateForm() {
    'use strict';


    var email = document.getElementById('email');
    var password = document.getElementById('password');


    if ( (email.value.length > 0) && (password.value.length > 0) ) {
        return true;
    } else {
        alert('Please complete the form!');
        return false;
    }

} 


function init() {
    'use strict';


    if (document && document.getElementById) {
        var loginForm = document.getElementById('loginForm');
        loginForm.onsubmit = validateForm;
    }

} 
window.onload = init;

Answer №1

For those who prefer to implement custom validation instead of relying on the browser's default required fields checking, simply eliminate the required attribute from your <input> tags.

View Demo

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

Manipulating the contents of a component's state by adding or removing objects

Currently, I am facing an issue with a list of check inputs where when they are selected and deselected, I am attempting to add or remove them from the state. However, I have noticed that when I deselect one item, the previously selected item is the one ...

Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

Creating a new tab within a window that is already open

I have an interesting challenge - I need to open a new tab in a window that was previously opened using window.open(). So, if the window is already open, I want to open a tab in that same window. I have attempted to reference the existing window to open a ...

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

Interpreting Multilayered JSON Objects using JQuery

Hello everyone! I've posted my sample json data below. While I am proficient in PHP, I am relatively new to jQuery. "data":{ "cipher":"true", "size":[ "2.2 Mb", "6.11 Mb", "9.25 Mb", ...

Avoiding drops in frame rates caused by socket.io in Node.js

I'm currently working on creating animations using html5 canvas. My goal is to have these animations replicated on any client connected to my server. To achieve this, I send the function to be called along with its arguments as a string and then use e ...

How can I alter the center point of an Object3D in Three.js?

I have a scenario where I am adding meshes dynamically to an Object3D. I'm curious if there is a way to obtain the center of the object so that I can apply rotations and translations evenly across the entire mesh, rather than having them centered on o ...

What is the best way to incorporate an environmental variable in my AngularJS controller?

My API Key is securely stored in my '.env' file to keep it hidden from Git. Here's a snippet of my .env file: API_TOKEN=secrettokengibberish When working on my Angular controller, I need to retrieve this variable for my AJAX call. This i ...

Implementing a new feature in the plugin panel to toggle CSS styling based on checkbox

Currently, I am working on a Wordpress plugin where I have integrated some styling options into the admin panel. Here's a look at what I have done: I want to achieve a functionality where clicking on a checkbox automatically applies the corresponding ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...

Give a response in ISO string

Hey everyone, I'm running into an issue when trying to access a date property in an array of objects from another component using props. When I try to convert it to a string using the 'toISOString()' method, I get an error saying 'toISO ...

AngularJS Cross-Origin Resource Sharing request with a customized header

I'm currently facing issues with enabling CORS on my server while using AngularJS. I am working with Angular version 1.2.16 and below is my server configuration: Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Cont ...

The final element is always the variable that is passed into the .on() function

Trying to create an event system similar to Backbone, I have set up an object like this: var events = { 'click .one': 'fnOne', 'click .two': 'fnTwo', 'click .three': 'fnThree' } For ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

Applying a CSS transition to transform properties excluding rotation effects

I'm looking to apply a transitional animation to an element's transform property without affecting the rotation. Here is the code snippet: <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js ...

Encountering an IE 8 error when attempting to follow a link

I am currently working on a Windows Server 2003 with IE 8. My website functions well on Firefox and Google Chrome. It also works fine on IE, except for one issue: There is a certain link that, when clicked, shows an error on page message in yellow at th ...

Contrast objects and incorporate elements that are different

In my scenario, I have a list of days where employees are scheduled to work. However, on the website, I need to display the remaining days as leave. In cases where an employee has two different shifts, there can be two elements in the object. var WorkDays ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

Unable to bind click eventListener to dynamic HTML in Angular 12 module

I am facing an issue with click binding on dynamic HTML. I attempted using the setTimeout function, but the click event is not binding to the button. Additionally, I tried using template reference on the button and obtaining the value with @ViewChildren, h ...