bcmcfc
bcmcfc

Reputation: 26745

How do I use a JS variable within JSON?

I'm attempting to create a postcode lookup JQuery script that'll be able to be used multiple times on a page, without having to duplicate the script for every address on the page. The Find button has the class "postcodeLookup" and the attribute "address" which is how I intended to get the script to populate the right address (it uses JQuery Populate plugin) & the inputs are named address[line1], where "address" is changeable (home[line1], office[line1], etc.).

The problem is how to get the JSON that populates the address to use the variable contents rather than the literal word "address"?

//postcode lookups
$(".postcodeLookup").click(function(){
    alert("I am The Postcode Finder...\nPretending to find the address...\nFound it!");
    var address = $(this).attr('address');
    $("form").populate({
        address: {
            line1: "First Line of Addr.",
            line2: "Line 2!",
            line3: "Line 3 of The Address",
            postcode: "PO1 1PO"
        }
    });
    $(".addressArea").slideDown('fast');
});

Upvotes: 2

Views: 2189

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

var addrName = "office";
var address = {};

address[ addrName ] = {
   line1: "First line",
   line2: "Line 2..."
};

$("form").populate( address );

Now, when addrName is office, that will be the same as writing

address['office'] = { }

... which, in turn, is exactly the same thing as writing

address.office = { }

And that little piece of knowledge will be immensely useful in all aspects of javascript.

For instance

for(var i = 0; i < 10; i++) {
    window['var' + i] = i;
}

Will actually create 10 variables in the window object (i.e. public variables) called var0, var1, ..., var9.

Ok, so that wasn't immensely useful, but you get the idea.

Upvotes: 6

zarko.susnjar
zarko.susnjar

Reputation: 2053

Probably you need to do something like this, usually jQuery plugins work this way:

line1: function(data) {return youVariable},

Upvotes: 0

Related Questions