Javascript is unable to locate a function that has been transformed from a string

Trying to change a string into a function without relying on eval() is proving to be troublesome. Whenever I pass the function name to the window object and check its type in JavaScript, it does not register as a function. Instead, I'm constantly met with a custom error message I've set up within the else statement: "Function not found: 1->validateLogin".

My custom dom_ready prototype:


dom_ready: function (inputFunc) {
    document.addEventListener("DOMContentLoaded", function () {
        try {
            inputFunc();
        } catch (e) {
            DN.errors.push(e.message);
        }
    });
},


function show_pass() {
   ...
}

function validateLogin(k) {
   ...
}

DN.DOM.dom_ready(function () {
var event_ids = [
    ["#login-form-dialog", "validateLogin", "submit", 1],
    ["#loginnotes", "validateLogin", "click", 1],
    ["#loginnotes2", "validateLogin", "click", 2],
    ["#show-pass", "show_pass", "click", ""],
]

for (var i = 0; i < event_ids.length - 1; i++) {

    var fN = window[event_ids[i][1]];

    if (typeof fN === 'function') {

        $(event_ids[i][0]).on(event_ids[i][2], function () {
            fN(event_ids[i][3]);
        })

    } else {
        console.log("Function not found: " + i + "->" + event_ids[i][1]);
    }
}
});

Answer №1

The issue you are facing is due to a specific syntax error that has been discussed in previous responses. To identify such errors, check the console for any error messages or use a linter to analyze your code. Relying on posting questions on platforms like Stack Overflow every time you miss a comma may not be the most efficient solution.

It's important to avoid passing function references using strings that correspond to their names and then having to search for them within the window object. Instead, directly pass the function reference itself (e.g., validateLogin). Unlike certain other programming languages, JavaScript treats functions as first-class citizens that can be easily referenced and passed around. Your revised code snippet would resemble the following:

DN.DOM.dom_ready(function () {
  var event_ids = [
    ["#login-form-dialog", validateLogin, "submit", 1]
                           ^^^^^^^^^^^^^
  ...

  for (var i = 0; i < event_ids.length - 1; i++) {
    var fN = event_ids[i][1];

Ensure that the function validateLogin is accessible when this ready function gets executed.

However, there is a fundamental issue that might hinder the execution of your code, particularly in the subsequent lines:

$(event_ids[i][0]).on(event_ids[i][2], function () {
  fN(event_ids[i][3]);
})

Here, the anonymous function refers to the variable i, which ends up at its maximum value of 3 by the time it gets executed during an event. Numerous discussions on Stack Overflow delve into this subject, but one simple solution is to utilize for (let i) if your environment supports let. Alternatively, refer to resources such as this thread.

Answer №2

Don't forget to include a comma after the first item in event_ids:

let event_ids = [
    ["#login-form-dialog", "validateLogin", "submit", 1], // <-- make sure to add comma
    ["#loginnotes", "validateLogin", "click", 1],
    ["#loginnotes2", "validateLogin", "click", 2],
    ["#show-pass", "show_pass", "click", ""]
]; // <-- also, it's recommended to end with a semi-colon here

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

Fetching JSON Data from Web Service using Ajax URL Field - A Simple Guide

I'm facing an issue while attempting to retrieve JSON Data from a web service using ajax url. This is how I have coded it so far: <script type="text/javascript> $('#kategoriTable').dataTable({ ajax: { u ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...

Utilizing ASP.NET with JavaScript to target elements by ID within an iframe

Struggling to populate my form within an iframe by inputting a value in a textbox and selecting an option from a dropdown menu. webform1 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...

How can you implement code that responds differently based on whether the user clicks the OK, cancel, or close button in a confirm dialog

What are three buttons in a confirm dialog box? How can JavaScript be used to perform different actions when the "ok" and "cancel" buttons are clicked, without performing any action when the dialog box is closed? ...

Deliver an additional parameter via mail using the bootstrap-fileinput feature

Is there a way to pass an additional variable to PHP using the POST method with bootstrap-fileinput? I have included the necessary CSS and JS files in my web project, and here is the HTML snippet: <input name="uploadfile" id="input-id" type="file" mul ...

What causes the to-do item underneath a crossed-off one to also be crossed out when the to-do item above is removed?

How come the todo item below a crossed one becomes crossed when a todo-item above is deleted? For instance: item1 item2 item3 item4 Mark item3 as crossed out: item1 item2 item3 X item 4 Delete item 2: item1 item3 item4 X What mistake did I make in m ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

What is the ideal location for the jsoncallback to be placed?

function initiate(){ $('#detailsPage').on('pageshow', function(event) { var username = getUrlVars()["username"]; //var username = "studentB"; $.getJSON('http://mywebsite.com/fetchStudent.php?username='+username+&a ...

What are the best strategies for addressing security risks in Axios versions 1.0.0 to 1.5.1 and those greater than or equal to 1.3.2?

After running npm install, I encountered a moderate vulnerability. How can I resolve this issue? 1 moderate severity vulnerability To fix all problems, run: npm audit fix Run `npm audit` for more information. # npm audit report axios 1.0.0 - 1.5.1 S ...

Error alert: The reference to emailjs is not recognized in the onsubmit function of HTMLFormElement

I'm currently attempting to utilize Emailjs as a client-side script for sending emails. However, I keep encountering the error "Uncaught ReferenceError: emailjs is not defined at HTMLFormElement.onsubmit". Below is the HTML code that is causing the i ...

Failure to trigger Ajax callback function

I am currently working on a form page that will be submitted using Ajax. The steps I have planned are: 1. Use Ajax to check if the email already exists 2. Verify if the passwords match 3. Switch to another "screen" if they do match 4. Final ...

Developing an Angular directive that accepts a function parameter using TypeScript

I've been attempting to integrate an Angular function parameter into a TypeScript directive, but it seems like my syntax is off. Here's an example of the directive code I'm working with: export class CustomDirective implements ng.IDirective ...

Tips for preventing multiple requests in your JavaScript search autocomplete feature

I'm currently using the Turbolinks.visit action with the help of $(document).on("input");... HTML <form id="mainSearch" method="get" autocomplete="off"> <input type="search" name="s" placeholder="Search" /> </form> Javascript ...

Are you able to locate <td>s with identical classes using just a portion of the string?

There are multiple classes in the <td>s of my table. I am looking to identify each <td> that contains a specific string. For instance: <table> <tr> <td class="hello there">foo</td> <td class=" ...

Swapping characters from the beginning and end of a specific string

Consider the following scenario: b*any string here* If this pattern is present, I would like to substitute b* at the beginning with <b>, and the * at the end with </b> (Ignore the backslash for SO site escaping). It's possible that ther ...

Instructions for selecting the initial year in the date of birth dropdown menu

I am working on code that displays date of birth values and I want to enhance it by adding another function in the JavaScript. However, I am unsure about the best approach to do so. The default age is set at 2000 and users cannot go any lower as the minim ...

Performance Issues Arise with Rapid Clicking [jQuery]

Having trouble with a gallery script I created that includes thumbnails, a large image, and navigation arrows. When you rapidly click on thumbnails or arrows during the transition, it causes delays in the process. The more clicks you make, the more noticea ...

How can I retrieve the content of a JSON file and store it in an attribute of my

Just starting out with Angular 2 (first day!) I'm working on a class that has 3 fields: id and name which are passed to the constructor, and a third field called data which should hold the content of a JSON file. export class Hero { id: string; ...

What is the best way to keep track of the number of checked checkboxes and add them to a separate div?

I need to select multiple checkboxes from different sections, count them, and then append the same number of sections to another div. ...