SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question string as variable/array name

    Hi there,

    Been looking around the old internet for an answer to this problem for about 3 hours now and I can't seem to find anything suitable.

    Here's the deal. I want to have a series of arrays that update on click. There are 9 sets of checkboxes, each within a parent div with a unique id. The id name is the same as the array name. When a checkbox is clicked my script checks the parent div's id, then modifies the correct array. At the moment I'm using a series of switch statements to discern the array from the id, like so:

    Code:
    var sausages = [], mash = [], gravy = []; //etc..
    $(':checkbox').click(function){
      switch($(this).parent().attr('id')){
        case 'sausages':
          sausages.push($(this).val());
          break;
        case 'mash':
          mash.push($(this).val());
          break;
        case 'gravy':
          gravy.push($(this).val());
          break;
        //etc..
      }
    });
    What I want to have is something along the lines of:
    Code:
    $(':checkbox').each(function(){
      var $(this).parent().attr('id') = [];
    }
    
    $(':checkbox').click(function(){
      $(this).parent().attr('id').push($(this).val());
    });
    I know in PHP you can use the following to a similar effect:
    PHP Code:
    foreach($array as $key => $value){
      $
    $key $value;

    Is that possible in javascript or am I being a little optimistic?

    Thanks in advance,
    Mike

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,095
    Mentioned
    28 Post(s)
    Tagged
    1 Thread(s)
    Hi Mike,

    You can assign a variable on an object using the array syntax when you have strings as keys. These are identical for example,
    Code javascript:
    var varName = 'name';
    obj.name == obj['name'] == obj[varName];
    so all you need is an object(can be window) if you want it in the global scope. Or something else.
    Code javascript:
    var data = {};
    ...
    var varName = $(this).parent().attr('id');
    data[varName] = [];
    window[varName] = [];
    This is my second favorite feature of javascript, nearly everything behaves like a hash.

  3. #3
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Brilliant, thanks!


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •