Sanya
Sanya

Reputation: 1280

jQuery pass array as argument in function

I am trying to pass an array as an argument in a function

See the --> fiddle <--

From what I've tested it seems the function is reading the argument as a string rather than an array. How do I pass the array as an argument in the function?

HTML

<button id='arr1'>Click for Array 1</button>
<button id='arr2'>Click for Array 2</button><br/><br/>

<div id='mainstuff'>
    <p>When you click button, text should be added</p>
</div>

jQuery

$(document).ready(function() {
    var arr1 = ["one", "two", "three"];
    var arr2 = ["eleven", "twelve", "thirteen", "fourteen"];

    $('button').click(function() {
        var myval = $(this).attr('id');
        showstuff(myval);        
    });


    function showstuff(myval) {
        var x = "<p>The new text is " + myval[2] + "</p>";
        $('#mainstuff').append(x);
    }

});

EDIT: Fiddle has been updated to fix syntax errors.

Upvotes: 4

Views: 21506

Answers (3)

Lochemage
Lochemage

Reputation: 3974

You would have to store your array variables in a common object (or the window scope, which is bad practice) that you can retrieve later:

var commonObject = new Object();
commonObject.arr1 = ["one", "two", "three"];
commonObject.arr2 = ["eleven", "twelve", "thirteen", "fourteen"];

Then to retrieve that variable by string name:

var myval = $(this).attr('id');
showstuff(commonObject[myval]);

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

You cannot pass in string values to be converted to objects directly. Instead store your arrays as a key-value pairs and then try to access them.

$(document).ready(function () {
    var arrays = {
         arr1 : ["one", "two", "three"],
        arr2 : ["eleven", "twelve", "thirteen", "fourteen"]
    };

    $('button').click(function () {
        var myval = $(this).attr('id');
        showstuff(myval);
    });


    function showstuff(myval) {
        var x = "<p>The new text is " + arrays[myVal][2] + "</p>;
        $('#mainstuff').append(x);
    }

});

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237827

You shouldn't do this. Don't try to call variables dynamically, i.e. without knowing their names. You can do it at a push in some circumstances, but it's a bad idea.

The best solution here is to use an object and square bracket notation to get a value from the object dynamically:

var values = {
    arr1: ["one", "two", "three"],
    arr2: ["eleven", "twelve", "thirteen", "fourteen"]
}

$('button').click(function() {
    var myval = this.id;
    showstuff(values[myval]);        
});

NB that I have changed $(this).attr('id') to this.id for much increased performance.

Upvotes: 5

Related Questions