Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page.

Even though there seems to be no errors in the login and register functions, I have a form with an input set to submit connected to a variable which listens for events.

Here is an example of my TypeScript login code:

    loginForm.addEventListener("submit", async (event) => {

        event.preventDefault(); // Prevent the default form submission behavior

        // Remove error message if it exists
        document.getElementById("error")?.remove();

        // Get form data
        const formData: FormData = new FormData(loginForm);
        const formDataObject: { [key: string]: string } = {};

        // Convert formData to a JavaScript object
        formData.forEach((value, key) => {
            formDataObject[key] = value as string;
        });

        const username: string = formDataObject["username"];
        const password: string = formDataObject["password"];

        try {
            const rows: any = await api.queryDatabase("SELECT * FROM user WHERE username = ? AND password = ?",

                [username], [password]);

            // If query returns any result, then log in
            if (rows[0]) {
                const user: any = rows[0];
                session.set("userId", user.userId);
                url.redirect("index.html");
            } else {
                // Throw wrong username or password error
                throw new Error("Wrong username or password");
            }
        }

        catch (reason: any) {
            // Create error message in login-popup
            const errorContainer: any = document.createElement("div");
            errorContainer.id = "error";
            const errorMessage: any = document.createTextNode(reason);
            errorContainer.appendChild(errorMessage);
            document.getElementById("login-popup")?.appendChild(errorContainer);
        }
    });
}

I tried implementing the same logic for the index using a navbar and anchor instead of a submit tag, but now it's not working.

TypeScript code:

function logout(): void{

    console.log(session.get("userId"));
    //const unorderedList: HTMLUListElement = document.getElementById("navlist") as HTMLUListElement;

    const logoutButton: HTMLAnchorElement = document.getElementById("logout") as HTMLAnchorElement;

    logoutButton.addEventListener("click",  async (event) =>{
        console.log("Clicked logout button");
        event.preventDefault(); // Prevent the default form submission behavior
        session.remove("userId");
        url.redirect("index.html");
    });
}

logout();

The first console log does return the user ID in the console, indicating a successful connection with the database.

HTML code:

<li class="hidden" id="logout"><a type="logout" id="logout" href="" >Logout</a></li>

I have tried various changes in variable types, IDs, positions, and names, but unfortunately, none seem to resolve the issue.

Answer №1

The snippet you've shared attempts to attach a logout event listener to an anchor element with the ID "logout". However, there is no built-in logout event in JavaScript and anchors are not form elements that can be submitted.

To resolve this issue, consider changing the event listener to respond to the click event on the anchor element. Additionally, you can remove the call to event.preventDefault() since there's no default action to prevent. Here's a revised version of the code:

function logout(): void { const logoutButton: HTMLAnchorElement = document.getElementById("logout") as HTMLAnchorElement;

logoutButton.addEventListener("click", async () => {
    session.remove("userId");
    url.redirect("index.html");
});

}

logout();

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

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

What sets apart 'export type' from 'export declare type' in TypeScript?

When using TypeScript, I had the impression that 'declare' indicates to the compiler that the item is defined elsewhere. How do these two seemingly similar "types" actually differ? Could it be that if the item is not found elsewhere, it defaults ...

Enumerate all interdependencies among 2 directories or libraries in an Angular application

I am currently working on a large Angular project and need to refactor some code by identifying dependencies between two specific folders/libs (using nx). Here is an example of the file structure: /apps /lib-1 a.service.ts b.component.t ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Issue with displaying Typescript sourcemaps on Android device in Ionic 2

Encountering a strange behavior with Ionic2. After deploying my app to a simulator, I am able to view the .ts file sourceMap in the Chrome inspect debugger. In both scenarios, I use: ionic run android https://i.sstatic.net/JarmI.png However, when depl ...

Make an http.patch request to the server using a Nativescript application

I am attempting to make an http.patch request to the server in my Nativescript application, which is built with Typescript and Angular2. The backend system is developed using Python(Django). Here is the code for my request: updateOrder(id, message) { ...

The message states that the variable "Chart" has not been defined

I have been attempting to integrate ChartJS with Angular2, but I keep encountering an error message stating that 'Chart is not defined'. I made sure to install the ChartJS typings and referenced them accordingly. Additionally, I included the char ...

There seems to be an issue in Angular as it is unable to retrieve /

I'm encountering an issue with my simple application where I am receiving the error message "Cannot GET /." Also, in the console, I see this error: TypeError: Cannot read property 'checked' of null at Object.SL_BBL_locer. I'm unsure ab ...

Closing Accordions Automatically

Hello everyone! I'm currently working on a NextJS project and facing an issue with my dynamic accordion component. I'm using typescript, and the problem lies in only one accordion being able to open at a time. How can I ensure that only the spec ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

Older versions of javascript offered the assurance of a promise

Working with TypeScript and the latest ECMAScript 6 feature Promise at the moment. I'm wondering if it's possible to use Promise even if my TypeScript code is compiled into an ECMAScript 3 js-file, considering that Promise wasn't available i ...

Refining a Collection of Possible Options

If I have an array of type Maybe<int>[] and want to extract only the values that are not None, what is the most efficient approach while ensuring TypeScript recognizes the output as int[]? It seems like declaring the result type as int[] is the way ...

Mastering the art of typing a member of an abstract generic class in Typescript with consideration for potential additional implementations

It's quite challenging to put into words, but essentially I aim to create a base abstract class outlining an abstract interface that must vary based on whether a derived class implements a specific interface or not. Here is a TypeScript playground de ...

The successful completion of an Angular2 HTTP request relies on the data obtained from a previous response

I developed a service that performs various http calls with different parameters. quote.service.ts getQuotes(){ let params = { "Type": "BasicDetail", } return this.http.post(this.url,params) .map(res => res.json()) } getOptio ...

Creating accurate JSON data using p-dropdown PrimeNG

I recently started learning Angular and encountered a situation while using the Java API: In my Release class, the category is not required (class Category). @Entity @Table(name = "release") public class Release { @Id @GeneratedValue(strategy = G ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

When I utilize a component to create forms, the React component does not refresh itself

One of the components I am working with is a form handling component: import React, { useState } from "react"; export const useForm = (callback: any, initialState = {}) => { const [values, setValues] = useState(initialState); const onCha ...

Arranging a 2D array of matchups to ensure an equal distribution of home and away matches for each team

I am in the process of developing a unique UEFA Champions League 24 'Swiss Model' tournament with 36 teams. Each team is set to compete against 8 different opponents, resulting in a total of 144 matches. I already have a list of matchups prepared ...