The global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value.

However, when called from a dynamically created function, it returns unknown.

onClick: function(val){
            for (i = 0; i < 
positions[this.selected].SHC.length; i++){
                var tag = 
positions[this.selected].SHC[i];
                var tagEl = 
document.createElement('p');

                console.log(this.selected) // CORRECT VALUE DISPLAYED HERE
                tagEl.onclick = function(){
                    console.log(this.selected) // RETURNS UNKNOWN HERE
                    for (j = 0; j < positions[this.selected].SHC.length; j++){

                        if (positions[this.selected].SHC[j] == this.innerHTML){
                            positions[this.selected].SHC.splice(j,1);
                        }
                    };
                ;}
                tagEl.textContent = tag;
                document.getElementById("uldshtags").appendChild(tagEl);
            }
        },

Is there a way to ensure that the global variable can also be accessed by dynamically created functions?

Answer №1

To ensure the correct value is accessed within an 'onclick' function, it is recommended to declare a variable and assign 'this' before the 'onclick' function. This variable can then be used inside the 'onclick' function.

      onClick: function (val) {
    for (i = 0; i <
        positions[this.selected].SHC.length; i++) {
        var tag =
            positions[this.selected].SHC[i];
        var tagEl =
            document.createElement('p');
        var that = this;
        console.log(this.selected) // RETURNS CORRECT VALUE
        tagEl.onclick = function () {
            console.log(that.selected) // RETURNS UNKNOWN
            for (j = 0; j < positions[that.selected].SHC.length; j++) {

                if (positions[that.selected].SHC[j] == this.innerHTML) {
                    positions[that.selected].SHC.splice(j, 1);
                }
            };

        }
        tagEl.textContent = tag;
        document.getElementById("uldshtags").appendChild(tagEl);
    }
}

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

Having trouble getting my HTML file and CSS styles to render properly in Chrome

Currently, I am in the process of developing a website and facing challenges with displaying CSS properties accurately. Despite seeking input from friends and users, my HTML file is not rendering as expected within various browsers such as Chrome, Edge, an ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Issue with updating onclick attribute of popover in Bootstrap 4

My goal is to design a popover in bootstrap 4 with a nested button inside it. However, when I update the data-content attribute of the popover with the button element, the element gets updated but the onclick attribute goes missing. I have experimented wi ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

Incorporating language modifications using the Laravel Vue Internationalization package

Hey there, I'm exploring Vue and attempting to create a multilingual application. During my research, I came across this package - https://github.com/xiCO2k/laravel-vue-i18n. I successfully installed it and managed to establish the connection for tran ...

Creating a reverse progress bar in HTML and Javascript that incorporates a countdown date

I'm struggling to find a way to create a progress bar that empties as it gets closer to the countdown date. I came across two different examples that I think could be merged, but I'm not sure how to do it: Countdown - https://www.jqueryscript. ...

In order to develop a JS class in React JS, I must import Scripts

I have a collection of SDK scripts that need to be included in the following manner: <script src="../libs/async.min.js"></script> <script src="../libs/es6-shim.js"></script> <script src="../libs/websdk.client.bundle.min.js ...

The body parser is causing issues with decoding base64 strings

When my mobile app sends a base64 string to my Express server via a POST request, the image is transmitted to a Google client endpoint. However, an error is returned saying: Provided image is not valid code: 400, 0|index | errors: [ 0|index | { 0 ...

Having trouble generating an image with JavaScript

I am currently working on incorporating an image onto a webpage using JavaScript. Surprisingly, even the alert('This function works!') is not displaying anything! What could be causing this issue? Please assist! <!DOCTYPE html> <html> ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Exploring the possibilities of infinite scroll in JavaScript using the Backbone framework

I've been grappling with this problem for three days straight. I've been attempting to incorporate scrolling into my backbone project using the https://github.com/paulirish/infinite-scroll plugin. Despite my best efforts to find a solution throu ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

Retrieve JSON data by making an AJAX request to a PHP file using the POST method

I am looking to extract data from a form using an AJAX call. The information is received in PHP as a string that looks like: 'fname':'abc','lname':'xyz','email':'','pass':'',& ...

Can custom HTML elements be designed to function similarly to standard ones?

What is the best way to create a custom HTML element that functions as a link without relying on inline Javascript? For instance: <x-button href="...">...</x-button> Can I develop an element like <x-button> that can accept an attribute ...

Troubleshooting await and async functions in Express.js applications

How can I create an array like the one shown below? [{ "item":"item1", "subitem":[{"subitem1","subitem2"}] },{ "item":"item2", "subitem":[{"subitem3","subitem4&q ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...

The drop-down menu is failing to display the correct values in the second drop-down

Having trouble with the update feature in this code. There are 2 textboxes and 2 dropdowns, but when selecting a course code, the corresponding values for the subject are not being posted. Can anyone assist? view:subject_detail_view <script type="te ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...