Skip to content

Instantly share code, notes, and snippets.

@wagenet
Created April 20, 2009 13:13
Show Gist options
  • Save wagenet/98527 to your computer and use it in GitHub Desktop.
Save wagenet/98527 to your computer and use it in GitHub Desktop.
// FieldNotes
// ==========
// Author: Peter Wagenet
// Description: Provides descriptions in text fields, removing them when the field is
// active and when the form is submitted.
//
// Sample Usage:
// <script type="text/javascript" charset="utf-8">
// document.observe("dom:loaded", function(){
// new FieldNotes('id_of_form', {
// id_of_field_1: "Description Text 1",
// id_of_field_2: "Description Text 2",
// id_of_field_3: "Description Text 3"
// },
// { notedClass: 'noted' });
// });
// </script>
FieldNotesList = $H();
var FieldNotes = Class.create({
initialize: function(form, fields, options) {
this.options = Object.extend({
noted_class: "noted"
}, options || {});
this.form = $(form);
this.fields = $H();
$H(fields).each(function(field_option){
field = $(field_option[0]);
note = field_option[1];
this.fields.set(field.identify(), new NotedField(this, field, note));
}.bind(this));
this.form.observe('submit', this.hideAllNotes.bind(this));
FieldNotesList.set(this.form.identify(), this);
},
showAllNotes: function() {
this.fields.values().invoke('showNote');
},
hideAllNotes: function() {
this.fields.values().invoke('hideNote');
}
});
var NotedField = Class.create({
initialize: function(field_notes, element, note) {
this.field_notes = field_notes;
this.field = $(element);
this.note = note;
this.showingNote = false;
this.field.observe('focus', this.focused.bind(this));
this.field.observe('blur', this.blurred.bind(this));
this.showNote();
},
blank: function() {
return this.field.value == '' || this.field.value == this.note;
},
notedClass: function() { return this.field_notes.options['noted_class'] },
showNote: function() {
if (this.blank() && !this.showingNote) {
this.showingNote = true;
this.field.addClassName(this.notedClass());
this.field.value = this.note;
}
},
hideNote: function() {
if (this.showingNote) {
this.showingNote = false;
this.field.removeClassName(this.notedClass());
this.field.value = '';
}
},
/* Aliases */
focused: function() { this.hideNote() },
blurred: function() { this.field_notes.showAllNotes() }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment