tags:

views:

46

answers:

2

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');
});
+2  A: 
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.

David Hedlund
Perfect, thank you.
bcmcfc
That trailing comma (after the `line2` property) on your first example will make IE fail. IE doesn't like dangling commas, in either object literals or array literals.
T.J. Crowder
@T.J. Crowder: quite right! i was about to add more properties, but figured that those were really peripheral to the point, so i narrowed it down, but missed the comma. good catch.
David Hedlund
@David: No worries. (+1, btw) I was going to remove the comment since it's now outdated, but then I thought, maybe it'll be useful to someone finding this later, although they'll have to sort of imagine what I'm talking about. :-)
T.J. Crowder
@T.J. Crowder: they can always browse through the revisions of the answer =) yes, it's a valuable comment, indeed, although people will have to chance upon it. i've definitely struggled with this before, in arrays :)
David Hedlund
A: 

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

line1: function(data) {return youVariable},
zarko.susnjar