form-attr.polyfill.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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').filter('[type=reset],[type=submit]').click(function() {
  47. var type = this.type.toLowerCase();
  48. if (type === 'reset') {
  49. // reset form
  50. form.reset();
  51. // for elements outside form
  52. $fields.each(function() {
  53. this.value = this.defaultValue;
  54. this.checked = this.defaultChecked;
  55. }).filter('select').each(function() {
  56. $(this).find('option').each(function() {
  57. this.selected = this.defaultSelected;
  58. });
  59. });
  60. } else if (type.match(/^submit|image$/i)) {
  61. $(form).appendField({
  62. name: this.name,
  63. value: this.value
  64. }).submit();
  65. }
  66. });
  67. });
  68. });
  69. })(jQuery);