jQuery: Form Plugin, Sweet… Almost

November 8, 2006 | 1 Comment

jqueryI am a recent convert to the powers of jQuery ever since Matt fell in love with it at "The Ajax Experience". The syntax and simplicity exceeds the combination of Prototype and Script.aculo.us that I was using.

By far one of the greatest features of jQuery is the ability for the community to create amazingly useful plugins. As I become dependent on many, I will highlight them here (mostly so I don't forget). The plugin I want to talk about right now is the form plugin from malsup.

Basically this plugin allows you to have a form be submitted through an XHR call. It uses the form's defined action URL to determine where to post the values and by default will update a specified div with returned data. It has additional flexibility to get returned data in XML or JSON if you would prefer. Go check out the example on his site, this is extremely simple to implement. This is exactly what I was looking for and I was quite happy, until I found a bug...

There is a problem with the internal formToArray() function when dealing with multi-select lists. If you are pre-selecting values in the list on load with some sort of server side language (PHP in my case), the pre-selected values will be submitted along with the newly selected user values. Obviously this is not what you would want to happen. The problem code occurs around 300 lines in:

JavaScript:
  1. if (t == 'select-multiple') {
  2.     jQuery('option:selected', this).each( function() {
  3.     a.push({name: n, value: this.value});
  4.     });
  5.     return;
  6. }

The jQuery search is finding more than it should. I have two ways in mind to resolve this issue. Most simply, you can add an if statement before the push, like this:

JavaScript:
  1. if (t == 'select-multiple') {
  2.     jQuery('option:selected', this).each( function() {
  3.     if(this.selected == true)
  4.         a.push({name: n, value: this.value});
  5.     });
  6.     return;
  7. }

This makes sense and is simple, yet it feels dirty since you receive more data from the search than necessary. I'm not certain about the efficiency, so here is another option:

JavaScript:
  1. if (t == 'select-multiple') {
  2.     for(var i=0;i<this.options.length;i++) {
  3.         if(this.options[i].selected==true)
  4.             a.push({name: n, value: this.options[i].value});
  5.     }
  6.     return;
  7. }

In this second one, we loop over all the elements in the multi-select to determine which are checked.

Like I said, I'm unsure which would yield the better performance, so hopefully someone will do the benchmarking and it can be rolled into the next version of this sweet plugin.

ajax, ajax experience, ajax form, form plugin, javascript, jquery, jquery form plugin, jquery plugin, jquery plugins, malsup, plugins, xhr

Tags: , , , , , , , , , , ,

Related: