Polyfill HTML5 form attribute (for input fields)

后端 未结 6 842
悲&欢浪女
悲&欢浪女 2020-12-19 03:44

This is the markup I use:


...
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 04:07

    The polyfill above doesn't take into account the Edge browser. I have amended it to use feature detection, which I have tested in IE7+, Edge, Firefox (mobile/desktop), Chrome (mobile/desktop), Safari (mobile/desktop), and Android browser 4.0.

    (function($) {
        /**
         * polyfill for html5 form attr
         */
    
        // detect if browser supports this
        var SAMPLE_FORM_NAME = "html-5-polyfill-test";
        var sampleForm = $("");
        var sampleFormAndHiddenInput = sampleForm.add($(""));     
        sampleFormAndHiddenInput.prependTo('body'); 
        var sampleElementFound = sampleForm[0].elements[0];
        sampleFormAndHiddenInput.remove();
        if (sampleElementFound) {
            // browser supports it, no need to fix
            return;
        }
    
        /**
         * Append a field to a form
         *
         */
        $.fn.appendField = function(data) {
          // for form only
          if (!this.is('form')) return;
    
          // wrap data
          if (!$.isArray(data) && data.name && data.value) {
            data = [data];
          }
    
          var $form = this;
    
          // attach new params
          $.each(data, function(i, item) {
            $('')
              .attr('type', 'hidden')
              .attr('name', item.name)
              .val(item.value).appendTo($form);
          });
    
          return $form;
        };
    
        /**
         * Find all input fields with form attribute point to jQuery object
         * 
         */
        $('form[id]').submit(function(e) {
          // serialize data
          var data = $('[form='+ this.id + ']').serializeArray();
          // append data to form
          $(this).appendField(data);
        }).each(function() {
          var form = this,
            $fields = $('[form=' + this.id + ']');
    
          $fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
            var type = this.type.toLowerCase();
            if (type === 'reset') {
              // reset form
              form.reset();
              // for elements outside form
              $fields.each(function() {
                this.value = this.defaultValue;
                this.checked = this.defaultChecked;
              }).filter('select').each(function() {
                $(this).find('option').each(function() {
                  this.selected = this.defaultSelected;
                });
              });
            } else if (type.match(/^submit|image$/i)) {
              $(form).appendField({name: this.name, value: this.value}).submit();
            }
          });
        });
    
    
      })(jQuery);
    

提交回复
热议问题