jquery plugin to convert form input to a javascript object graph

29Oct08

Client side javascript validation often ends up being  ugly and really boring ..while on the serverside validations usually tend to be more domain related ,something like “order.Qty > 0″ on the serverside endsup looking something ugly like “document.get(…….).val()….”

I ended up writing a jquery plugin which reads the form inputs and converts it into an object graph based on the name attribute, so for an form with the following  inputs

<input  name="order.customerName"  />
<input  name="order.orderItem.qty"  />

you could just say

 var order = $('#myform').params2Object();
 test(order.customerName ==='john');
 test(order.orderItem.qty > 0 );

Here is the actual plugin code ..HTH

jQuery.fn.params2Object = function(){
    var d = this.serializeArray()
    var data = {};
    for (var i = 0; i < d.length; i++) {
        var tokens = d[i].name.split('.');
        _setValue(data, tokens, d[i].value);
    }
    return data;

    function _setValue(obj, tokens, value, index){
        if (tokens.length == 1) {
            if (typeof index != 'undefined') {
                obj[index] = obj[index] ||
                {};
                obj[index][tokens[0]] = value;
            }
            else {
                obj[tokens[0]] = value;
            }
        }
        else {
            var prop = _getProperty(tokens[0]);
            obj[prop.name] = obj[prop.name] || (prop.isArray ? [] : {});
            _setValue(obj[prop.name], tokens.slice(1, tokens.length), value, prop.index);
        }
    }

    function _getProperty(token){
        var arraySplit = token.split('[');
        if (arraySplit.length > 1) {
            var propName = arraySplit[0];
            var index = arraySplit[1].split(']')[0];
        }
        else {
            var propName = token;
        }
        return {
            name: propName,
            index: index,
            isArray: token.indexOf(']') > 0
        };

    }

};

About these ads


6 Responses to “jquery plugin to convert form input to a javascript object graph”

  1. What tamplate do you use in your blog? Very interesting articles

  2. Hallo! buy nolvadex on the net http://www.stumbleupon.com/stumbler/med-brother/ buy liquid nolvadex Remember me to your wife.

    I haven’t seen you for weeks. buy chemical citrate nolvadex research tamoxifen buy nolvadex in the usa
    buy online nolvadex Please, thank your sister for me.

  3. Awesome blog! Do you have any tips and hints for aspiring writers?
    I’m hoping to start my own website soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or
    go for a paid option? There are so many choices
    out there that I’m completely overwhelmed .. Any tips? Appreciate it!

  4. Thanks , I have recently been searching for info about this topic for a while and yours is the greatest I have came upon till now.
    However, what about the bottom line? Are you
    certain concerning the supply?

  5. Greetings! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when viewing from my iphone 4. I’m trying to find a
    theme or plugin that might be able to fix this problem.

    If you have any recommendations, please share. Cheers!

  6. Heya i’m for the first time here. I came across this board and I to find It really helpful & it helped me out much. I’m hoping to offer one thing back
    and aid others such as you aided me.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: