2

I have many html-inputs and a very big object with lots of information.

Many of those inputs are directly linked to a specific string in the object. E.g.:

<input name="alpha_beta_gamma" type="input" val="newstring" />

and

  obj = {
         alpha: {
             beta: {
                 gamma: 'oldString'
             }
         },
         stuff2: {
             whatever: {
                 weathertoday: 'rainy',
                 sun: false
             },
             phone: '1234567'
         }
  }

the checkbox field for the value "sun" would have the name "stuff2_whatever_sun" but the "phone" field the name "stuff2_phone" and the "gamma" input field the name "alpha_beta_gamma".

Hope you guys get me :)

...and I will use a jQuery focusout event:

 $('input.specialClass').live('focusout', function(){
      obj[whatevercomeshere] = $(this).val();
 });
3
  • Can you clarify the question? are you saying the input's name attribute is a method name on some object that you want to call? Commented Jun 24, 2011 at 15:19
  • yes. in this case "obj" is the first level, which is always the same, "alpha" is the second, "beta" the third" ect.. the thing is, that it can be two arguments ("alpha_beta") or e.g. seven! Commented Jun 24, 2011 at 15:21
  • I am guessing that you are really trying to ask how you are going to index the object in order to properly update it. We can't address an issue like that without understanding your large object. You'll have to be more detailed if this is the case. Commented Jun 24, 2011 at 15:23

3 Answers 3

2
$('input.specialClass').live('focusout', function(){
  var name = $(this).attr('name');
  var o = obj, parts = name.split("_");
  $.each(parts, function(k, v) {
    if(k == parts.length - 1) {
       o[v] = $(this).val();
    } else {
       o = o[v];
    }
  });  
});
Sign up to request clarification or add additional context in comments.

Comments

1

You might want to use eval:

$('input').each( 
   function() {
        var $this = $(this);
        $this.val(eval("obj." + $this.attr('name').replace(/_/g, '.'));
   }
);

1 Comment

exactly what I needed but backwards. Thanks for the eval tip.
0

Here's one method:

    var obj = {},
        name2json = function(o, name, val){
            var prop = name.splice(0, 1);
            o[prop] = o[prop] || {};
            if(name.length === 0){
                o[prop] = val;
            }else{
                name2json(o[prop], name, val);
            }
        };
    $('input.specialClass').live('focusout', function(){
        name2json(obj, this.name.split('_'), this.value);
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.