Prototype Radio Button Serialization Bug

October 8th, 2007

It turns out that my favorite JavaScript library has a rather weird chink in its otherwise impregnable armor. The Form.Serialize method makes a complete hash (no not an object hash, a right royal mess kind of hash) of serializing radio buttons. Google of course came to the rescue with this very excellent fix from Rex Chung.

This works great if you’ve got one set of radio buttons, I had an unknown number to deal with. So here is a slightly modified version that uses Prototype’s findAll:

Form.getInputs('formName','radio').findAll(function(rad){ return rad.checked; }).each(function(rad) {
     //Deal with each radio button here by referencing the method argument "rad"
     alert(rad.value);
});

Works like a charm.

Scriptaculous Draggables

October 18th, 2006

Started messing with the most excellent Scriptaculous JavaScript library yesterday and almost immediately ran into a very frustrating problem. The Draggable Class exposed by the library has some annoying behavior built in by default. When you set revert to true it has this animation where it moves back to its original location.

I was trying to build a drag and drop toolbox and the effect I was looking for was along the lines of dragging it and dropping it into a particular location and then it reappearing back at the original location. So the toolbox lets you drag individual items over to the main area and then the item reappears where it was taken from.

Well after several hours of digging around in the internals of the Scriptaclous JavaScript files I have the solution, so here it is for the rest of humanity to enjoy:

new Draggable(element,{revert:true, reverteffect: function(element, top_offset, left_offset) {
  toff = top_offset;
  loff = left_offset;
  new Effect.Fade(element, {duration: 0.75, afterFinishInternal: function (effect) {
    new Effect.Move(effect.element, {x: -loff, y: -toff, duration: 0.0, afterFinishInternal: function(effect) {
      new Effect.Appear(effect.element, {duration: 0.75})
}}) }}) }});

The Fade and Appear durations can be tweaked but I found 0.75 to be perfect for what I was trying to achieve. I’ll probably post a link to the finished app when I’m done.