Can I use 'div id' as the name for my array?

For a demonstration, please check out this jsfiddle: jsfiddle.net/rflfn/uS4jd/

Here is another attempt: jsfiddle.net/rflfn/T3ZT6/

I am utilizing SMOF to build a Wordpress theme. I need to create a function that changes certain values when a link is clicked. However, when I try to create an array with the name of the div, it returns a null value...

HTML:

<a class="button" id="settext1">Some Link</a>
<br />

<a class="button" id="settext2">Another Link</a>
<br />

<a class="button" id="settext3">Link 3</a>
<br />

jQuery:

$(document).ready(function(){
    col_settext1['field_id1']='#FF0000';
    col_settext1['field_id2']='#00FFFF';

    txt_settext1['field_id3']='Some Text Here';
    txt_settext1['field_id4']='Another Text Here';

    txt_settext2['field_id5']='Some Text Here';

    col_settext2['field_id6']='Another Text Here';

    chk_settext2['field_id7']="checked";
});

$('.button').click(function(){
    $myclass = this.id;

    $col = 'col_' + $myclass;
    $txt = 'txt_' + $myclass;
    $chk = 'chk_' + $myclass;

    // Issue arises here!
    $col = new Array();
    $txt = new Array();
    $chk = new Array();

    alert($col);
    alert($col[1]);

    for (id in $col) {
        alert(id);
    }
    for (id in $txt) {
        
    }
    for (id in $chk) {
        
    }

});

Is it possible to use the name of the div as an array name? Any suggestions or alternative methods to solve this issue are appreciated.

Answer №1

For a scenario where you aim to generate dynamic variable names based on specific parameters, it is recommended to utilize the following code in place of "$col = new Array();"

window[$col] = new Array();
window[$txt] = new Array();

and so forth...

Answer №2

It seems like the issue you're facing is that you are not assigning the variable names to the new array correctly based on your query.

During this stage:

$myclass = this.id;

$col = 'col_' + $myclass;
$txt = 'txt_' + $myclass;
$chk = 'chk_' + $myclass;

You end up with $col = "col_id", $txt = "txt_id", $chk = "chk_id".

In essence, each of these variables is linked to a string value.

Then, you proceed to do:

$col = new Array();
$txt = new Array();
$chk = new Array();

At this point, each variable is associated with a brand new empty array.

The correct approach would be:

$col = new Array();
$col[0] = "col_" + $myclass;

You should follow the same for the rest. By doing so, you will have a new array with one element, which is "col_id", assigned to the $col variable.

After these changes, you will have arrays named $col, $txt, and $chk containing the id name.

If your intention is to generate dynamic variable names (although it's unclear if this is necessary), you can utilize Window.

Answer №3

Seems like a simple issue, my jQuery knowledge is limited and I've been struggling for two whole days to get this working with no success. For those who understand it, this would probably take five minutes. I wrote another code, all I need is for the alert to display the correct value, so I can implement my original code.

When I click on button1, I expect to see the alert "text 1", but nothing happens.

http://jsfiddle.net/rflfn/N4a2h/

html

<a class="button" id="arr1">Button1</a>
<a class="button" id="arr2">Button2</a>
<a class="button" id="arr3">Button3</a>

Jquery

$('.button').click(function () {

    var window[myvar] = this.id;
    window[myvar] = new Array(); // I need use ID as array name

    // Code for button1
    arr1['value1'] = 'text 1';
    arr1['value2'] = 'text 2';

    // Code for button2
    arr2['value3'] = 'text 3';
    arr2['value4'] = 'text 4';

    // Code for button3
    arr2['value5'] = 'text 5';
    arr2['value6'] = 'text 6';

    // Click on Button1, the alert below need show "text 1"
    alert(window[myvar['value1']]); // "text 1"

    // alert(myvar['value1']);
});

I came across this solution at http://www.sitepoi...post5174213 but couldn't make it work either.

I also tried using this method from Dynamic jQuery variable names but had no luck.

Answer №4

I sought assistance on the jQuery forum and was thrilled to finally discover the solution at this link.

For a demonstration, visit this JSFiddle page.

HTML Code Snippet:

<a class="button" data-arr="arr1">Button1</a> |
<a class="button" data-arr="arr2">Button2</a> |
<a class="button" data-arr="arr3">Button3</a>

jQuery Code Snippet:

var arr = {
    arr1: {value1:"test 1", value2:"test 2"},
    arr2:{value3:"test 3", value4:"test 4"},
    arr3:{value5:"test 5", value6:"test 6"}
}
$('.button').click(function () {
    var call_array = arr[$(this).data("arr")]
    $.each(call_array, function (index, value) {
        alert('Array Value: ' + index + '        Array Content: ' + value);
    });
});

A big thank you for all of your help!

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

How to Initialize a Multidimensional Array with Various Data Types in Swift

I'm exploring how to build a structure using a multidimensional array. Initially, I was able to successfully create a structure for a 1D array: struct example1 { var user: [String] } However, I encountered an issue when attempting to create an ...

The mystery behind my disappearing cookies and sessions during Ajax requests in Internet Explorer 9

I am facing an issue with session cookies where they work fine in Chrome and Firefox, but in IE9 with AJAX requests, I lose all session cookies. When making a direct request to view: public class AddressController : Controller { [MvcSiteMapNode(Title ...

Adding a request parameter to an ajax Request for a jQuery dataTable that has been initialized from JSON and mapped by Spring can be achieved by including

I have a jQuery dataTable that is initialized from jSON and mapped by a Spring framework. Currently, I am not passing any parameters and retrieving all information. However, I now need to pass a single String to the Java method, most likely through a requ ...

Issue with correctly showcasing the elements within an array

In the following code snippet, data and images are being saved to $varcontent[$i]["content"] and $vacontent[$i]["images"]. However, when I try to display both outside of the loop, only $varcontent[$i]["content"] is shown correctly. The print_r function d ...

A guide to implementing an analytics system by leveraging multiple applications

My front-end application, which runs on Rails 4 + Postgres, is referred to as FRONT_APP. I also have another application for statistics, running on Rails 4 + Mongodb, which is called STATISTICS_APP. Within my FRONT_APP, I utilize the following XHR query f ...

Spinning divs using JavaScript when the mouse hovers over them, and then returning them to their original position when the mouse moves

I am looking to create a functionality where a div rotates when the mouse enters it and returns to its original position when the mouse leaves. Everything works fine when interacting with one div, but as soon as I try hovering over other divs, it starts gl ...

having difficulty choosing a particular identifier from a JSON string

I'm currently working on a project to create an admin page for managing client information. However, I've encountered an issue where I am unable to select the client's unique ID to display all of their information on a separate page. On the ...

Discovering the exact measurement of "remaining space" in absolute units with flexbox techniques

I am faced with a dilemma that is leaving me uncertain. Within a flexbox layout, specifically column-oriented, there are three children: top, middle, and bottom. The challenge arises in the middle child where I must embed a third-party component that requ ...

Choosing a dropdown option with a CSS Selector

Here is the code snippet I am currently working with: import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.o ...

I am looking to design a pair of Carousels that will be positioned right next to

Is it possible to set up two Carousels next to each other? https://i.sstatic.net/Dv7PB.png <div class="row"> <div class="col-md-2"></div> <div class="col-md-8"> <div id="Carousel" class="carousel slide"> ...

Maintaining the scrolling behavior and preserving added class even after refreshing the page

I am facing an issue with an element on my page that adds a class when the user scrolls past a certain point and removes it when scrolling back up. The problem arises when I refresh the page after the class has been added, it doesn't persist until I s ...

Exploring the depths of multidimensional arrays in PHP to display their contents

I am currently delving into PHP arrays, specifically multidimensional arrays, and I have encountered a stumbling block. Below is an example of a sample multidimensional array: Array ( [0] => Array ( [venue] => Chicago ...

Unable to use $.parseJSON() on a string containing src="" or id="" attributes

When looking at the code snippet below, I am able to use the $.parseJSON() method: var myString = '{ "Header": "<p>some content</p>"}'; var modelJsonObject = $.parseJSON(myString); However, I encounter an issue when the value of "He ...

Adjust the height of the Twitter Widget to be proportionate to the height of its parent div dynamically

I have integrated the Twitter widget into my library management system, but I am facing an issue with its fixed height. Is there a way to make the height dynamic through CSS? Any suggestions on how this can be achieved will be greatly appreciated. Below ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

What is the best way to implement horizontal content scrolling when an arrow is tapped in mobile view?

I recently created a JS Fiddle that seems to be working fine on desktop, but in mobile view, the square boxes have horizontal scrolling. Here are the CSS codes I used for this particular issue: @media only screen and (max-width: 767px) { .product-all-con ...

Ways to extend div to fill the rest of the page's vertical space

Apologies, my search has yielded many results, but none that directly address my specific issue. It appears that there is a proliferation of div-height problems on this platform. :-( Here is the layout I am working with for testing purposes: <!DOCTYPE ...

Looping CSS text animation with typing effect

I am struggling with a CSS code that types out text, but it only does so once and I need it to repeat infinitely. Despite adding animation-iteration-count: infinite;, it still doesn't work as intended. Another issue is that it slows down at the end. H ...

What could be causing my images to appear incomplete when using a background image with the style property?

Why are the images not appearing in full when I use the background-image URL style property? What is displayed on the page: https://i.sstatic.net/SwOGq.jpg body { background-image: url("../Bilder/ikkephotoshopped.jpg"), url(". ...

assign a category to the initial item in the array

I need assistance with jQuery array elements... <div id="holder"> <div class="X">X</div> <div class="X">X</div> <div class="X">X</div> <div class="Y">Y</div> <div class="Y ...