When the onclick event is triggered, it leads to the execution

Currently, I am developing a demonstration movie application where I have implemented onclick events using a function to retrieve movie-related data. However, I am encountering an issue when clicking on the specific links I need to work with, as it returns an undefined function. Below is the code snippet:

    function getMovieList(key,value) { console.log(key,value)}
    
    function getLanguages() {
        const languagesList = document.querySelector("[languages]");
        
        const languagesArray = [
            ["en-US", "english"],
            ["it", "italian"],
            ["de", "german"],
            ["hi", "indian"],
        ];
    
        const languagesMap = new Map();
    
        languagesArray.forEach( languages => {
            const [idLanguage,language] = languages;
            languagesMap.set(idLanguage,language);
    
            languagesList.innerHTML += `
             <li class="capitalize" onclick="getMovieList(with_original_langauge=${idLanguage}, ${language})">
                <a href="index.html" language-id="${idLanguage}">${language}</a>
            </li>`;
       
        } );
    }
getLanguages()

Upon inspecting my links, I can see that the arguments are correctly assigned. However, when clicking on them, I receive an error stating that my function is undefined and thus unable to retrieve the values. Could you please help me understand why this is happening?

I also attempted to use window.onload to ensure the function is loaded prior to interacting with it, but unfortunately, it did not resolve the issue.

Answer №1

When the getMovieList() function is called asynchronously, it means that the default action of the <a> link occurs before the function runs.

To prevent this default action, you can use event.preventDefault(); in the event handler and manually change the href within the function itself.

function getMovieList() {
  alert('movie list');
  location.href="index.html";
  }
<li>
   <a href="index.html" onclick="event.preventDefault();getMovieList()">language</a>
</li>

Answer №2

UPDATE : I have revised my response after reviewing your recent changes!

It seems like there's a piece of code that needs to include an actual location.href in the function.

The current setup only triggers an alert with some URL parameters for demonstration purposes.

    let languagesListDiv;
        
    let languagesArray = [
            ["en", "english"],
            ["it", "italian"],
            ["de", "german"],
            ["hi", "indian"]
        ];
    
    let languagesMap = new Map();
    let result = "";
    
    window.addEventListener("DOMContentLoaded",run);
        
    function getMovieList(key,value){
        console.log("key = " + key + ", value = " + value)
    }
    function alertMovieList(key,value){
        alert("location.href=\"http://yourLinkHere.test?key=" + key + "&value=" + value + "\"")
    }
    function run(e){
        languagesListDiv = document.getElementById("languagesListDiv");
        getLanguages();
    }
    function getLanguages() {
    languagesArray.forEach( languages => {
    languagesListDiv.innerHTML += `<li class="capitalize"><a href="index.html"  onclick="event.preventDefault();alertMovieList('${languages[0]}','${languages[1]}')">key = ${languages[0]}, value = ${languages[1]}</a></li>`;
    getMovieList(languages[0],languages[1]);
        });
    }
<ul id="languagesListDiv">
    
</ul>

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

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...

Retrieve the number of rows in the table component

I'm in need of getting the row count from a table component that I have built using vuejs. My goal is to display the row count outside of the table component structure. The issue with the code snippet below is that it doesn't show the correct row ...

Error in Internet Explorer when attempting to close a Fancybox iframe that plays a YouTube video

Even the FancyApps page itself contains the error mentioned below. If you visit using Internet Explorer 9, for example, follow these steps: Go to Internet Options > Advanced > Disable script debugging (Internet Explorer). Then click on the YouTube ( ...

Steps for generating an array entry containing an ObjectId and a Number

I am a newbie when it comes to mongodb and I am attempting to create an entry like this: { "resources": [ { "amount": 1, "resource": { "_id": "61be82b9549b4ede ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

What is the best way to sort inertia data on the client-side?

Looking for a solution with my component that receives data, I have the following setup in my controller: route::get('/', function() { return inertia('foo', ['data' => Model::all()]) }); Within my Vue component: <templa ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Mobile device users experiencing issues with jQuery scroll up and down functionality

Currently, I am utilizing jQuery to identify when a user is scrolling the mouse wheel up or down. Below is my code: $(window).bind('mousewheel DOMMouseScroll', function(event){ if (event.originalEvent.wheelDelta > 0 || event.originalEvent ...

What is the process for obtaining a component's ref using JavaScript event propagation?

Here is a code snippet I am working with: const dailyRef = createRef(); const monthlyRef = createRef(); const annuallyRef = createRef(); const handleBillingCycleClick = ({target}) => { const value = target.dataSet.value // How can I access the clic ...

Creating a communication bridge between a Chrome extension and an Angular application on a webpage

There's a chrome extension I've been working on that alters the Dom of webpages. However, I'm dealing with a page built in Angular, which means I need to adjust the scope of the element. How would I go about doing this? ...

Discovering and choosing the appropriate course

I am facing a situation where I need to specifically select an element with the class .foo, but there are two anchor tags, both having the class .foo. However, I only want to select the one without the additional .bar class. How can I achieve this? <a ...

I am having trouble unzipping the file

I encountered an issue while attempting to download a .zip file from Discord and extracting it using the decompress package. Despite not returning any errors, the package did not get extracted as expected. (The file was saved and downloaded correctly) co ...

jQuery parallax effect enhances scrolling experience with background images

My website features a parallax design, with beautiful high-resolution images in the background that dominate the page. Upon loading the site, the landing page showcases a striking, large background image alongside a small navigation table ('about&apos ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

The 'npm start' command is failing to recognize the changes made to the

I am embarking on a new node application journey, starting with the package.json below, which is quite basic. { "name": "mynewnodeventure", "version": "1.0.1", "description": "Exploring node", "main": "index.js", "start": "node server. ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Is it possible to create a d3 gauge chart showcasing data with both labels and

We've been on the hunt for a radial chart that resembles the one shown below. What makes this chart stand out is the clear display of percentage values. Despite our search efforts over three days, we have yet to come across anything using the d3.js li ...

Error message: Unable to set the uploaded file in the specified state within a React application

I am currently working on a react application that involves file uploads. My goal is to update the state variable with the uploaded file in either .docx or .pdf format as soon as it is uploaded. However, when I try to set the state, it shows up as undefine ...

Encountering challenges with CORS implementation in a test application

I am struggling with an issue while trying to send a request to a website for ping. I have tried using jsonp, but it's not working as expected. I attempted to implement cors, but I keep getting the error message "No 'Access-Control-Allow-Origin&a ...

Create a new <div> element using jQuery when the user

There is a collection of div elements listed below: <li class="comment"> <div class="comment-body" id="comment-body"> <div class="comment-author vcard"> <div class="lightbox-photo"> ...