Is there a way for my script to interpret a subscripted output as a predefined variable name?

Is there a way to make the output of my string be interpreted as a variable rather than displayed as text?

Despite researching the issue, I am struggling to find a solution as a beginner in this subject.

}
function showDetailedView(currentDiv) {
    var popframe = document.getElementById(currentDiv);
    var picture = currentDiv.substring(0, currentDiv.length - 5);
    var pic1 = "Arachnobot mk II";
    var pic2 = "Tyson Droid";
    var pic3 = "Dancer Bot";
    var pic4 = "Skinny Fingers";
    var pic5 = "Abomination";
    var pic6 = "Dog";
    var pic7 = "Smart Scratch";
    var pic8 = "Soccer Bots";
    var pic9 = "Butler Bot";
    var pic10 = "Peanut Gallery";
    var pic11 = "Statue Bot";
    var pic12 = "Gang Boys"; 
    var pic13 = "Nuclear Machine of Mass Destruction";
    var pic14 = "Eye Roll Droid";
    var pic15 = "Pet";
    popping = popframe.id;
    popframe.id = "popout";
    popframe.innerHTML = "<br /><TABLE><TR><TH rowspan='3'><img 
src='http://" + window.location.hostname + 
                            "/aprilla/"+currentDiv.substring(0, 
currentDiv.length - 5)+".jpg' width='250'><TH align='left'>Robot Type: 
<TH align='left'>" +
                            currentDiv.substring(0, currentDiv.length - 
5)+ "<TR><TH align='left'>Description: <TH align='left'> 'They do robot 
stuff' <TR></TABLE> ";

    var nameholder = "popout";
    var unpopped = document.getElementById(nameholder);
    unpopped.onmouseout = hideDetailedView;

}

The expected behavior was for

currentDiv.substring(0, currentDiv.length - 5)+
to return values like pic1, pic2, pic3, etc. which would then correspond to predefined variable names such as pic1 corresponding to Arachnobot mk II and so on. However, instead of converting to the respective variables, it simply displays the text pic1, pic2, pic3, etc.

Answer №1

substring function in JavaScript returns a string. It is recommended to use

window[currentDiv.substring(0, currentDiv.length - 5)]
.

var id = "pic1withsometext";
var pic1 = "lorem";

document.querySelector('p').innerHTML = window[id.substring(0,4)];
<p>Some random paragraph</p></codee></pre>
</div>
</div>
</p>

<p><div>
<div>
<pre class="lang-js"><code>var id = "pic1withsometext";
var pic1 = "lorem";

// This approach does not work as expected
document.querySelector('p').innerHTML = id.substring(0,4);
<p>Some random paragraph</p>

For more information, refer to this resource - Convert string to variable name in JavaScript

Answer №2

Here are some key points to help you understand what may be going wrong in your code:

function showDetailedView(currentDiv) {
    var popframe = document.getElementById("currentDiv");
    // Make sure to use quotes when finding an ID to avoid returning a variable instead
    var picture = window[currentDiv.substring(0, currentDiv.length - 5)]; 
    // Instead of just calling it, add "window[currentDiv.substring(0, currentDiv.length - 5)]" as "substring" only returns a string
    
var pic1 = "Arachnobot mk II";
var pic2 = "Tyson Droid";
var pic3 = "Dancer Bot";
var pic4 = "Skinny Fingers";
var pic5 = "Abomination";
var pic6 = "Dog";
var pic7 = "Smart Scratch";
var pic8 = "Soccer Bots";
var pic9 = "Butler Bot";
var pic10 = "Peanut Gallery";
var pic11 = "Statue Bot";
var pic12 = "Gang Boys";
var pic13 = "Nuclear Machine of Mass Destruction";
var pic14 = "Eye Roll Droid";
var pic15 = "Pet";
popping = popframe.id;
popframe.id = "popout";

// Use single backward quotes below to maintain the original HTML structure inside the variable for better viewing and error identification
popframe.innerHTML = `
              <br>
        <TABLE>
          <TR>
            <TH rowspan="3">
              <img src="http://" ` + window.location.hostname + ` "/aprilla/ "` + picture + ` ".jpg" width="250">
              <TH align="left">Robot Type:
                <TH align="left">` + picture + `
                </TH>
              </TH>
            </TH>
          </TR>
          <TR>
            <TH align="left">Description:
              <TH align="left">
                They do robot stuff
              </TH>
            </TH>
          </TR>
        </TABLE>
              `;

var unpopped = document.getElementById("popout");

unpopped.onmouseout = hideDetailedView;

}

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

Verify if a value is present in an array or falls within specified range of values

My goal is to input a value and determine if it exists in an array or falls within a specified range of values within the array. I then want to retrieve the index of the lower range value. For instance, consider the following array: dataArr = [10, 20, 30 ...

The click function is not functioning properly when trying to integrate a jQuery Ajax HTTP request

Here is my query: I am trying to make an Ajax request from within a click function using jQuery (as shown in the example below). However, no data is being retrieved even though I am alerting it through the success function. Could you please guide me on wh ...

What is the process for defining the value in a select query?

http://jsfiddle.net/WcJbu/ I would like the favoriteThing selector to update with the current selection when choosing a person. <div ng-controller='MyController'> <select ng-model='data.selectedPerson' ng-options='pe ...

Navigate to Element ID with Nuxt.js on click

Currently, I am in the process of developing a Nuxt application and facing a challenge. I want the page to automatically scroll down to a specific element after clicking on a button. Interestingly, the button and the desired element are located within diff ...

Creating dynamic object rotation based on a new pivot point using Three.js

In Three.JS, I've successfully created a spiral with downward movement. However, I am struggling to implement the knocking motion. https://i.sstatic.net/VrykN.gif var planeGeometry = new THREE.PlaneGeometry(10,10); var planeMaterial = new THREE.Mesh ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

Is there a PHP function that functions similarly to JavaScript's "array.every()" method?

As I work on migrating JavaScript code to PHP, I am facing the challenge of finding a replacement for the array.every() function in PHP. I have come across the each() function in PHP, but it doesn't quite meet my requirements. ...

What is the reason behind my titles being triple the length they should be?

Here is my personal website The titles are appropriately set for the About College section Note: Utilizing Purl library for this purpose var seg2 = ''; if (url.segment(2) == 'college-life') seg2 = "College Life"; else if (url.seg ...

Conceal email address within HTML code

Similar Inquiry: What is the best way to hide an email address on a website? I've been contemplating ways to keep my email address secure on my website, including using AJAX to request it from the server after key validation and then simulating H ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

What is the process for obtaining a Facebook page ID using the Facebook page name?

Can someone please explain the process of obtaining a Facebook page ID from the Facebook page name? I noticed on this website that it displays the number of likes based on the Facebook page name. If anyone has any insight on how to achieve this, I would ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

Making a REST API call with an ID parameter using Angular

I am currently working on an Angular application that interacts with a REST API. The data fetched from the API is determined based on the customer ID, for example: api/incident?customer_id=7. I am unsure of how to incorporate this into the API URL and serv ...

Executing a JavaScript file within the Meteor JS ecosystem

Is there a way to execute a JavaScript file on the server side in a meteor JS environment? Providing some background information: I am looking to automatically insert a document into a mongo database. While I know how to do this in meteor through event-dr ...

Setting up a new event handler for an ng-repeat element

I am completely new to Angular! I want to implement a simple event in a form element created by ng-repeat with a specific value. Here is the HTML code: <div class="labels"> <div class="checkbox-element" ng-repeat="suggestN ...

Guide to setting up page.js

I am eager to incorporate page.js into my project. However, it seems like it requires some type of build system, so I'm not able to locate a single page.js file to include in my page and immediately begin using. page('/',index) Does anyone ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

Sending a Nan alert regarding a JSON attribute

I recently completed a project using Angular4 that involves connecting to a nodeExpressJS server to retrieve JSON data and update the object with new information. Below is the onSubmit function from the addemployeeform. onSubmit(formValue: any) { cons ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

What causes a ReferenceError when attempting to retrieve the class name of a React component?

Take a look at my React component located in index.js: import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render() { return ( <div className="App"> <h1>Hello, ...