using val method to set properties from Object

I am confused about how to properly use val method. My book says $(v).val(obj[name]); will set the value of the field from the value of the property. However, I am not clear about what this means. Here is the code I am having trouble understanding. It is designed to repopulate a form's fields back to its original values. I would appreciate a step by step explanation as I am still very new to jQuery. Thanks

fromObject:function(obj){
    $.each(this.find(':input'),function(i,v){
        var name = $(v).attr('name');
        if (obj[name]){
            $(v).val(obj[name]); //does this set the property as the value?
        } else {
            $(v).val('');
        }
    });
}

Answers 1

  • I think the problem is that you are not familiar with the bracket notation for accessing an objects properties.

    Suppose I have a form data object like obj = {name:"bob"}

    We usually access the name like obj.name; // we get bob

    It can be done like obj['name'] as well. This is used when the property name is not a proper variable name, for example

    obj = { "contacts[]": ["bob","john"] }
    
    obj['contacts[]'] // we get ["bob","john"]
    obj.contacts[] // syntax error   
    

    or when the property name you want to access is dynamic, like your case: You want to access the property corresponding to the value of name property. We can't use the . notation here because we don't know what the property name (value of name attribute ) is going to be.

    So the confusing line of code: $(v).val(obj[name]); is a mix of both:

    first we assign the value of name property to a variable name.
    When the value of name property is "contacts[]", $(v).val(obj[name]); is equivalent to $(v).val(obj["contacts[]"]); which evaluates to $(v).val(["bob","john"]);


Related Articles