Skip to main content

Bug Tracker

Side navigation

#11567 closed feature (plugin)

Opened April 08, 2012 02:14PM UTC

Closed April 08, 2012 04:58PM UTC

Add reset() method for partially/fully resetting form inputs

Reported by: SineSwiper Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.7.1
Keywords: Cc:
Blocked by: Blocking:
Description

Working code:

$.fn.extend({
   reset: function(makeBlank) {
      this.each(function() {
         var el   = $(this);
         switch(this.nodeName.toUpperCase()) {
            case 'INPUT':
               this.checked = makeBlank ? false : this.defaultChecked;
               // fall-through
            case 'TEXTAREA':
               this.value   = makeBlank ? ''    : this.defaultValue;
               return true;
            case 'OPTGROUP':
            case 'OPTION':
               el = el.parents('SELECT');
               // fall-through
            case 'SELECT':
               el.find('OPTION').each(function(i) {
                  this.selected = makeBlank ? false : this.defaultSelected;
                  if (this.defaultSelected && !el[0].multiple && !makeBlank) {
                     el[0].selectedIndex = i;
                     return false;
                  }
               });
               return true;
            case 'LABEL':
               var id   = el.attr('for');
               var list = el.find('INPUT, SELECT, TEXTAREA');
               if (id) list.unshift( $(id)[0] );
               list.reset();
               return true;
            case 'FORM':
               if (makeBlank) el.find('INPUT, LABEL, SELECT, TEXTAREA').reset();  // jQuery's reset()
               else           this.reset();                                       // JS FORM's reset()
               return true;
            default:
               el.find('FORM, INPUT, LABEL, SELECT, TEXTAREA').reset();
               return true;
         }
      });
      return this;
   }
});

This will search for and reset any form inputs in its path. Resetting means either making everything blank, or resetting it to its defaults, depending on the 'makeBlank' setting. You can choose to only reset part of the inputs, or the entire form, or all forms on the page.

Given that this sort of functionality involves basic FORM manipulation, IMO, this should be a core jQuery method.

Attachments (0)
Change History (1)

Changed April 08, 2012 04:58PM UTC by rwaldron comment:1

resolution: → plugin
status: newclosed

That's a lot of code for a new feature that doesn't appear to have high (or any) demand. Better to offer as a plugin