``Javascript: Solving the issue of Event Handler onlick not triggering

Completing an assignment for my university, I created a basic Static Log-In Form using JavaScript and HTML. However, I am facing an issue with the onclick event handler that is not functioning properly. Despite trying various solutions and even attempting to use the 'button' tag, the problem persists. I require assistance in identifying where I may be making a mistake. Below is the code I have written:

<html>
<head>
    <title> Test File </title>

    <script>

        function checkEmailField()
        {
            if (document.username.sender.value.length < 1)
            {
                window.alert("Caution! You did not enter your Email");
            }
        }
    </script>

</head>

<body bgcolor="pink">

    <table align="center">
            <tr>
                <td align="center">
                    <b> <h1> Fill out the form below to log in: </h1> </b>

                    <form name="logIn" method="post" action="sendMailScriptURL">
                        <table border="1">
                            <tr>
                                <td> <b> Email: </b> </td>
                                <td> <input type="text" name="username" size="50"> <br> </td>
                            </tr>

                            <tr>
                                <td> <b> Password: </b> </td>
                                <td> <input type="password" name="password" size ="50"> </td>
                            </tr>

                            <tr>
                                <td> <b> Logging in from: </b> </td>
                                <td>    
                                    <input type="radio" name="from" value="campus"> Campus <br>
                                    <input type="radio" name="from" value="home"> Home                      
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I am using: </b> </td>
                                <td>
                                    <select name="OS" size="1">
                                        <option value="Windows" selected> Windows
                                        <option value="Linux/UNIX"> LINUX/UNIX
                                        <option value="Mac OSX"> Mac OSX
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I have: </b> </td>
                                <td>
                                    <input type="checkbox" name="have" value="Computer"> Computer <br>
                                    <input type="checkbox" name="have" value="Mobile"> Mobile <br>
                                    <input type="checkbox" name="have" value="Printer"> Printer <br>
                                    <input type="checkbox" name="have" value="Scanner"> Scanner
                                </td>
                            </tr>

                            <tr>
                                <td> <button onclick="checkEmailField()"> Log In </button></td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>
</body>
</html>

Answer №1

There are two issues to address here: firstly, the way you are attempting to access the value of your email field in the "checkEmailField" function is incorrect. You should be accessing the forms attribute of the document object, followed by your specific form, and then the desired field. It seems like including "sender" in there may have been a typo.

The second issue is that you only have one button in your form. By default, most browsers will treat this single button as a submit button. This means that when the button is clicked, the form will submit regardless of the input. To prevent submission when the email field is empty, you need to return false in the "checkEmailField" function and also return the result of the function in your onclick handler.

Consider using this revised version instead:

<html>
<head>
    <title> Test File </title>

    <script>

        function checkEmailField()
        {
            if (document.forms.logIn.username.value.length < 1)
            {
            window.alert("Caution! You did not enter your Email");
            return false;
            }
            return true;
        }
    </script>

</head>

<body bgcolor="pink">

    <table align="center">
            <tr>
                <td align="center">
                    <b> <h1> Fill out the following form to log in:</h1></b>

                    <form name="logIn" method="post" action="sendMailScriptURL">
                        <table border="1">
                            <tr>
                                <td><b>Email:</b></td>
                                <td><input type="text" name="username" size="50"><br></td>
                            </tr>

                            <tr>
                                <td><b>Password:</b></td>
                                <td><input type="password" name="password" size ="50"></td>
                            </tr>

                            <tr>
                                <td><b>Logging in from:</b></td>
                                <td>    
                                    <input type="radio" name="from" value="campus"> Campus <br>
                                    <input type="radio" name="from" value="home"> Home                      
                                </td>
                            </tr>

                            <tr>
                                <td><b>I am using:</b></td>
                                <td>
                                    <select name="OS" size="1">
                                        <option value="Windows" selected> Windows
                                        <option value="Linux/UNIX"> LINUX/UNIX
                                        <option value="Mac OSX"> Mac OSX
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td><b>I have:</b></td>
                                <td>
                                    <input type="checkbox" name="have" value="Computer"> Computer <br>
                                    <input type="checkbox" name="have" value="Mobile"> Mobile <br>
                                    <input type="checkbox" name="have" value="Printer"> Printer <br>
                                    <input type="checkbox" name="have" value="Scanner"> Scanner
                                </td>
                            </tr>

                            <tr>
                                <td><button onclick="return checkEmailField();"> Log In </button></td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>
</body>
</html>

I trust this solution will be of assistance!

Answer №2

To resolve the issue with the JavaScript function call, it is recommended to place your JavaScript code before the closing <body> tag.

<html>
<head>
    <title> Test File </title>

</head>

<body bgcolor="pink">

    <table align="center">
            <tr>
                <td align="center">
                    <b> <h1> Fill out the form below to log in: </h1> </b>

                    <form name="logIn" method="post" action="sendMailScriptURL">
                        <table border="1">
                            <tr>
                                <td> <b> Email: </b> </td>
                                <td> <input type="text" name="username" size="50"> <br> </td>
                            </tr>

                            <tr>
                                <td> <b> Password: </b> </td>
                                <td> <input type="password" name="password" size ="50"> </td>
                            </tr>

                            <tr>
                                <td> <b> Logging in from: </b> </td>
                                <td>    
                                    <input type="radio" name="from" value="campus"> Campus <br>
                                    <input type="radio" name="from" value="home"> Home                      
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I am using: </b> </td>
                                <td>
                                    <select name="OS" size="1">
                                        <option value="Windows" selected> Windows
                                        <option value="Linux/UNIX"> LINUX/UNIX
                                        <option value="Mac OSX"> Mac OSX
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I have: </b> </td>
                                <td>
                                    <input type="checkbox" name="have" value="Computer"> Computer <br>
                                    <input type="checkbox" name="have" value="Mobile"> Mobile <br>
                                    <input type="checkbox" name="have" value="Printer"> Printer <br>
                                    <input type="checkbox" name="have" value="Scanner"> Scanner
                                </td>
                            </tr>

                            <tr>
                                <td> <button onclick="checkEmailField()"> Log In </button></td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>
    <script>

        function checkEmailField()
        {
            if (document.username.sender.value.length < 1)
            {
            window.alert("Attention! Please enter your email address.");
            }
        }
    </script>
</body>
</html>

Answer №3

document.username will throw an error because it doesn't match anything:

Cannot read property 'sender' of undefined
. To solve this, you can search for the username in the DOM using a traversal method. One easy way is to assign an id to the input field like this:
input id="username" name="username"
and then use document.getElementById (or you can also use document.querySelector). Check out this quick jsFiddle example: https://jsfiddle.net/tztyky6g/

Answer №4

Revise the code

document.username.sender.value.length < 1

To

var email = document.forms[0].elements["username"].value;

document object includes a forms property. In this HTML, there is one form accessible through document.forms[0]. To access the username input, use

document.forms[0].elements["username"]
.

You are not defining any property named username on the document object. Thus, trying to access document.username will return undefined because the username property does not exist within the document object.

Revised Code:

<html>
<head>
    <title> Test File </title>

    <script>

        function checkEmailField()
        {
            var email = document.forms[0].elements["username"].value;
            if (email.length < 1)
            {
                 window.alert("Caution! You did not enter your Email");
                 return false;
            }
        }
    </script>

</head>

<body bgcolor="pink">

    <table align="center">
            <tr>
                <td align="center">
                    <b> <h1> Fill the following form to log in: </h1> </b>

                    <form name="logIn" method="post" action="sendMailScriptURL">
                        <table border="1">
                            <tr>
                                <td> <b> Email: </b> </td>
                                <td> <input type="text" name="username" size="50"> <br> </td>
                            </tr>

                            <tr>
                                <td> <b> Password: </b> </td>
                                <td> <input type="password" name="password" size ="50"> </td>
                            </tr>

                            <tr>
                                <td> <b> Logging in from: </b> </td>
                                <td>    
                                    <input type="radio" name="from" value="campus"> Campus <br>
                                    <input type="radio" name="from" value="home"> Home                      
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I am using: </b> </td>
                                <td>
                                    <select name="OS" size="1">
                                        <option value="Windows" selected> Windows
                                        <option value="Linux/UNIX"> LINUX/UNIX
                                        <option value="Mac OSX"> Mac OSX
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td> <b> I have: </b> </td>
                                <td>
                                    <input type="checkbox" name="have" value="Computer"> Computer <br>
                                    <input type="checkbox" name="have" value="Mobile"> Mobile <br>
                                    <input type="checkbox" name="have" value="Printer"> Printer <br>
                                    <input type="checkbox" name="have" value="Scanner"> Scanner
                                </td>
                            </tr>

                            <tr>
                                <td> <button onclick="checkEmailField()"> Log In </button></td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>
</body>
</html>

Answer №5

It's important to update your function for proper element access.

 function verifyEmailField() {
    var emailElement = document.getElementsByName('username');
    if (emailElement[0].value.length < 1) {
        window.alert("Warning! Please enter your Email");
    }
}

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

Sending newly generated arguments

Currently, I am developing a NodeJS/Express listener where inputs are dynamically created while my connectListener function is being formed: app.get('/server/:args', function(req, res) { res.sendFile(__dirname + '/index.html'); / ...

"Encountering a black screen when connecting a camera to a GLTF object in Three.JS

Hey guys, I've been working with Three.JS and I've run into a bit of trouble with the camera. I'm trying to attach the camera to an imported model object, and it seems like it's attaching but there are some issues. The shadows seem to b ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Is it possible to independently verify the results of promises within a $.when(...) function without regard to the overall outcome?

Take a look at this example: $.when(a1, a2, a3, a4, .....) .done(function (){alert('done')}) .fail(function (){alert('fail')}); If all promises from a1 to ax were successful, I can manage and handle all the data within t ...

Submission method of a stateless component in Redux form

Should I keep this component stateless or should I convert it to a stateful component? import React from "react"; import { Field, reduxForm } from "redux-form"; import { connect } from "react-redux"; import RaisedButton from 'material-ui/RaisedButton ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...

Proper method for retrieving and displaying information from a targeted JSON through an API

Utilizing a third-party API requires specifying the desired fields in the request. For instance: axios.get("APIURL", { params: { fields: ["username", "phone", ...etc] } }) The response is typically structured like this: { "data": [{ ...

Discover the index of the row when the value in the dropdown list is updated

I'm faced with a challenge regarding an HTML Table that contains a dropdown list in every row. I would like the background of each row to change whenever the value in the dropdown list is modified. Below is the code snippet: <table id="table1"> ...

Exploring the versatility of Angular Directives for numerous selections

My website has a footer section: <footer> <div class="container"> <div class="contents"> <div class="logo-copyright"> <div class="footer-logo"> <i class="footer-logo gradient">< ...

Maintain daily data that can be updated in JSON format

I'm working on a web application that utilizes client-side MVC with backbone.js and Spring on the server side. I have a scenario where I require data that needs to be updated daily or every couple of days. The data will be used on the client side for ...

In need of assistance understanding why using methods from a mongoose schema functions smoothly in one section of my Node.js application, but encounters errors in other areas

I have defined a user schema in my application which includes two methods: getSnapshot() and getLastTweetId() user.js const mongoose = require('mongoose') const getLastTweetId = require('../utilities/getLastTweetId') const ...

RSS feed showing null xml data with jQuery

Working on coding a straightforward RSS feed utilizing jquery and pulling data from Wired. Everything appears to be functioning correctly, except for one issue - after the description, an unknown value of NaN is appearing in the result. It seems to be comi ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Unable to insert form and view upon file upload click

After attempting a file upload within a form, I noticed that upon submission the data is not being inserted into the database as expected. Additionally, when trying to access the table on another page and clicking on a specific file, the redirection does n ...

Tips for Chrome developers on locating elements' styles

My div is being dynamically set by JavaScript and the Chrome developer tools show it as: elements.style{ display: block; } I want to change this display setting to 'none', but I'm unable to locate the specific code in the JavaScript file. ...

Drop down selection causing Highchart display issue

I'm experimenting with displaying a div that contains a Highchart in this code snippet: http://jsfiddle.net/ot24zrkt/129/ This line should reveal the container: $('#container' + $(this).val()).show();? Fiddle code: <script src="https:/ ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Alternate. (individually)

Issue with Running Program I've been struggling to get my program to run correctly. The task at hand is to have the program display only one question at a time. But no matter what I try, clicking on all questions displays all the answers simultaneous ...

Turn off the observeChanges feature for the update query

I am trying to disable the observeChanges method on a collection when updating it. Does anyone have a solution for this? I came across the Meteor Docs which mentioned using reactive: false for the .find() method. Is there a similar option for the .update( ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...