form-attr.polyfill.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (function($) {
  2. $(function() {
  3. /**
  4. * polyfill for html5 form attr
  5. */
  6. // detect if browser supports this
  7. var sampleElement = $('[form]').get(0);
  8. var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
  9. if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11) {
  10. // browser supports it, no need to fix
  11. return;
  12. }
  13. /**
  14. * Append a field to a form
  15. *
  16. */
  17. $.fn.appendField = function(data) {
  18. // for form only
  19. if (!this.is('form')) return;
  20. // wrap data
  21. if (!$.isArray(data) && data.name && data.value) {
  22. data = [data];
  23. }
  24. var $form = this;
  25. // attach new params
  26. $.each(data, function(i, item) {
  27. $('<input/>')
  28. .attr('type', 'hidden')
  29. .attr('name', item.name)
  30. .val(item.value).appendTo($form);
  31. });
  32. return $form;
  33. };
  34. /**
  35. * Find all input fields with form attribute point to jQuery object
  36. *
  37. */
  38. $('form[id]').submit(function(e) {
  39. // serialize data
  40. var data = $('[form=' + this.id + ']').serializeArray();
  41. // append data to form
  42. $(this).appendField(data);
  43. }).each(function() {
  44. var form = this,
  45. $fields = $('[form=' + this.id + ']');
  46. $fields.filter('button, input')
  47. .filter('[type=reset],[type=submit],[type=image],button')
  48. .click(function() {
  49. var type = this.type.toLowerCase();
  50. if (type === 'reset') {
  51. // reset form
  52. form.reset();
  53. // for elements outside form
  54. $fields.each(function() {
  55. this.value = this.defaultValue;
  56. this.checked = this.defaultChecked;
  57. }).filter('select').each(function() {
  58. $(this).find('option').each(function() {
  59. this.selected = this.defaultSelected;
  60. });
  61. });
  62. } else {
  63. $(form).appendField({
  64. name: this.name,
  65. value: this.value
  66. }).submit();
  67. }
  68. });
  69. });
  70. });
  71. })(jQuery);