views:

58

answers:

3
var cur_storage_unit = $('#storage_unit').val();

$('.size_unit').change(function() {
    var id = $(this).attr('id');

    //This is how I want it to work, but not sure how
    'cur_' + id = $(this).val();
});

The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!

+3  A: 

you can create a new property on an object using a string as a key

var myObj = {};
myObj['cur_'+id] = $(this).val();

so in your case you would want an object with a known name where you can add dynamically named properties.

lincolnk
And of course, this can apply to the global object, which in browsers is `window`. So `window['cur_'+id] = ...`. Better, though, to avoid cluttering the global namespace and put all of your symbols in one uber-symbol as lincolnk is suggesting here.
T.J. Crowder
+3  A: 

If it's global you can do window['cur_'+id];

antimatter15
+3  A: 

You're probably better off using an Object, and storing it in there.

var cur_storage_unit = $('#storage_unit').val();

var values = {};  // storage for multiple values

$('.size_unit').change(function() {
    var id = this.id;

    values['cur_' + id] = this.value;  // store this value in the "values" object
});

// Accessible via values object
alert( values["cur_theid"] );
patrick dw
Recommend not making `cur_storage_unit` a global.
T.J. Crowder
@T.J. Crowder - Is it global? I assume this is all taking place within jQuery's `ready()`.
patrick dw
@patrick dw: Then you're assuming facts not in evidence. :-) There's nothing to suggest that in the OP's question. BUT! I mistakenly thought when originally commenting that you'd moved it out a level, which looking at the question you didn't, it was already out there.
T.J. Crowder
@T.J. Crowder - Fair enough. :o) It is such a common practice that I tend to take it for granted.
patrick dw
@patrick dw: :-)
T.J. Crowder
Yes you are correct it is under .ready and thank you for the help!
bmck