Before I start I must confess, I love the mootools framework. It becomes my choice of js framework. Ok, lets start. For a cute project I will release soon, I convert many ajax post to a json posts and for that reason I needed a function that converts submit params directly to a JSON object. After some minutes Ive enhanced the Element class with a new function called toJSON. What does this do ? After traversing all html elements it creates a new array and return a JSON.encode object ready to be send to an url. Here is the function:

Element.implement({
  toJSON: function() {
    var json = {};
    this.getElements(‘input, select, textarea’, true).each(function(el){
      if (!el.name || el.disabled || el.type == ‘submit’ || el.type == ‘reset’ || el.type == ‘file’) return;
      var value = (el.tagName.toLowerCase() == ‘select’) ? Element.getSelected(el).map(function(opt){
        return opt.value;
      }) : ((el.type == ‘radio’ || el.type == ‘checkbox’) && !el.checked) ? null : el.value;
      $splat(value).each(function(val){
        if (typeof val != ‘undefined’) json[el.name] = encodeURIComponent(val);
      });
    });
    return JSON.encode(json);
  }
});

 

  • Share/Bookmark