jquery.form.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /**
  2. * EasyUI for jQuery 1.5.5.4
  3. *
  4. * Copyright (c) 2009-2018 www.jeasyui.com. All rights reserved.
  5. *
  6. * Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php
  7. * To use it on other terms please contact us: info@jeasyui.com
  8. *
  9. */
  10. /**
  11. * form - EasyUI for jQuery
  12. *
  13. */
  14. (function($){
  15. /**
  16. * submit the form
  17. */
  18. function ajaxSubmit(target, options){
  19. var opts = $.data(target, 'form').options;
  20. $.extend(opts, options||{});
  21. var param = $.extend({}, opts.queryParams);
  22. if (opts.onSubmit.call(target, param) == false){return;}
  23. // $(target).find('.textbox-text:focus').blur();
  24. var input = $(target).find('.textbox-text:focus');
  25. input.triggerHandler('blur');
  26. input.focus();
  27. var disabledFields = null; // the fields to be disabled
  28. if (opts.dirty){
  29. var ff = []; // all the dirty fields
  30. $.map(opts.dirtyFields, function(f){
  31. if ($(f).hasClass('textbox-f')){
  32. $(f).next().find('.textbox-value').each(function(){
  33. ff.push(this);
  34. });
  35. } else {
  36. ff.push(f);
  37. }
  38. });
  39. disabledFields = $(target).find('input[name]:enabled,textarea[name]:enabled,select[name]:enabled').filter(function(){
  40. return $.inArray(this, ff) == -1;
  41. });
  42. disabledFields.attr('disabled', 'disabled');
  43. }
  44. if (opts.ajax){
  45. if (opts.iframe){
  46. submitIframe(target, param);
  47. } else {
  48. if (window.FormData !== undefined){
  49. submitXhr(target, param);
  50. } else {
  51. submitIframe(target, param);
  52. }
  53. }
  54. } else {
  55. $(target).submit();
  56. }
  57. if (opts.dirty){
  58. disabledFields.removeAttr('disabled');
  59. }
  60. }
  61. function submitIframe(target, param){
  62. var opts = $.data(target, 'form').options;
  63. var frameId = 'easyui_frame_' + (new Date().getTime());
  64. var frame = $('<iframe id='+frameId+' name='+frameId+'></iframe>').appendTo('body')
  65. frame.attr('src', window.ActiveXObject ? 'javascript:false' : 'about:blank');
  66. frame.css({
  67. position:'absolute',
  68. top:-1000,
  69. left:-1000
  70. });
  71. frame.bind('load', cb);
  72. submit(param);
  73. function submit(param){
  74. var form = $(target);
  75. if (opts.url){
  76. form.attr('action', opts.url);
  77. }
  78. var t = form.attr('target'), a = form.attr('action');
  79. form.attr('target', frameId);
  80. var paramFields = $();
  81. try {
  82. for(var n in param){
  83. var field = $('<input type="hidden" name="' + n + '">').val(param[n]).appendTo(form);
  84. paramFields = paramFields.add(field);
  85. }
  86. checkState();
  87. form[0].submit();
  88. } finally {
  89. form.attr('action', a);
  90. t ? form.attr('target', t) : form.removeAttr('target');
  91. paramFields.remove();
  92. }
  93. }
  94. function checkState(){
  95. var f = $('#'+frameId);
  96. if (!f.length){return}
  97. try{
  98. var s = f.contents()[0].readyState;
  99. if (s && s.toLowerCase() == 'uninitialized'){
  100. setTimeout(checkState, 100);
  101. }
  102. } catch(e){
  103. cb();
  104. }
  105. }
  106. var checkCount = 10;
  107. function cb(){
  108. var f = $('#'+frameId);
  109. if (!f.length){return}
  110. f.unbind();
  111. var data = '';
  112. try{
  113. var body = f.contents().find('body');
  114. data = body.html();
  115. if (data == ''){
  116. if (--checkCount){
  117. setTimeout(cb, 100);
  118. return;
  119. }
  120. }
  121. var ta = body.find('>textarea');
  122. if (ta.length){
  123. data = ta.val();
  124. } else {
  125. var pre = body.find('>pre');
  126. if (pre.length){
  127. data = pre.html();
  128. }
  129. }
  130. } catch(e){
  131. }
  132. opts.success.call(target, data);
  133. setTimeout(function(){
  134. f.unbind();
  135. f.remove();
  136. }, 100);
  137. }
  138. }
  139. function submitXhr(target, param){
  140. var opts = $.data(target, 'form').options;
  141. var formData = new FormData($(target)[0]);
  142. for(var name in param){
  143. formData.append(name, param[name]);
  144. }
  145. $.ajax({
  146. url: opts.url,
  147. type: 'post',
  148. xhr: function(){
  149. var xhr = $.ajaxSettings.xhr();
  150. if (xhr.upload) {
  151. xhr.upload.addEventListener('progress', function(e){
  152. if (e.lengthComputable) {
  153. var total = e.total;
  154. var position = e.loaded || e.position;
  155. var percent = Math.ceil(position * 100 / total);
  156. opts.onProgress.call(target, percent);
  157. }
  158. }, false);
  159. }
  160. return xhr;
  161. },
  162. data: formData,
  163. dataType: 'html',
  164. cache: false,
  165. contentType: false,
  166. processData: false,
  167. complete: function(res){
  168. opts.success.call(target, res.responseText);
  169. }
  170. });
  171. }
  172. /**
  173. * load form data
  174. * if data is a URL string type load from remote site,
  175. * otherwise load from local data object.
  176. */
  177. function load(target, data){
  178. var opts = $.data(target, 'form').options;
  179. if (typeof data == 'string'){
  180. var param = {};
  181. if (opts.onBeforeLoad.call(target, param) == false) return;
  182. $.ajax({
  183. url: data,
  184. data: param,
  185. dataType: 'json',
  186. success: function(data){
  187. _load(data);
  188. },
  189. error: function(){
  190. opts.onLoadError.apply(target, arguments);
  191. }
  192. });
  193. } else {
  194. _load(data);
  195. }
  196. function _load(data){
  197. var form = $(target);
  198. for(var name in data){
  199. var val = data[name];
  200. if (!_checkField(name, val)){
  201. if (!_loadBox(name, val)){
  202. form.find('input[name="'+name+'"]').val(val);
  203. form.find('textarea[name="'+name+'"]').val(val);
  204. form.find('select[name="'+name+'"]').val(val);
  205. }
  206. }
  207. }
  208. opts.onLoadSuccess.call(target, data);
  209. form.form('validate');
  210. }
  211. /**
  212. * check the checkbox and radio fields
  213. */
  214. function _checkField(name, val){
  215. var cc = $(target).find('[switchbuttonName="'+name+'"]');
  216. if (cc.length){
  217. cc.switchbutton('uncheck');
  218. cc.each(function(){
  219. if (_isChecked($(this).switchbutton('options').value, val)){
  220. $(this).switchbutton('check');
  221. }
  222. });
  223. return true;
  224. }
  225. cc = $(target).find('input[name="'+name+'"][type=radio], input[name="'+name+'"][type=checkbox]');
  226. if (cc.length){
  227. cc._propAttr('checked', false);
  228. cc.each(function(){
  229. if (_isChecked($(this).val(), val)){
  230. $(this)._propAttr('checked', true);
  231. }
  232. });
  233. return true;
  234. }
  235. return false;
  236. }
  237. function _isChecked(v, val){
  238. if (v == String(val) || $.inArray(v, $.isArray(val)?val:[val]) >= 0){
  239. return true;
  240. } else {
  241. return false;
  242. }
  243. }
  244. function _loadBox(name, val){
  245. var field = $(target).find('[textboxName="'+name+'"],[sliderName="'+name+'"]');
  246. if (field.length){
  247. for(var i=0; i<opts.fieldTypes.length; i++){
  248. var type = opts.fieldTypes[i];
  249. var state = field.data(type);
  250. if (state){
  251. if (state.options.multiple || state.options.range){
  252. field[type]('setValues', val);
  253. } else {
  254. field[type]('setValue', val);
  255. }
  256. return true;
  257. }
  258. }
  259. }
  260. return false;
  261. }
  262. }
  263. /**
  264. * clear the form fields
  265. */
  266. function clear(target){
  267. $('input,select,textarea', target).each(function(){
  268. if ($(this).hasClass('textbox-value')){return;}
  269. var t = this.type, tag = this.tagName.toLowerCase();
  270. if (t == 'text' || t == 'hidden' || t == 'password' || tag == 'textarea'){
  271. this.value = '';
  272. } else if (t == 'file'){
  273. var file = $(this);
  274. if (!file.hasClass('textbox-value')){
  275. var newfile = file.clone().val('');
  276. newfile.insertAfter(file);
  277. if (file.data('validatebox')){
  278. file.validatebox('destroy');
  279. newfile.validatebox();
  280. } else {
  281. file.remove();
  282. }
  283. }
  284. } else if (t == 'checkbox' || t == 'radio'){
  285. this.checked = false;
  286. } else if (tag == 'select'){
  287. this.selectedIndex = -1;
  288. }
  289. });
  290. var tmp = $();
  291. var form = $(target);
  292. var opts = $.data(target, 'form').options;
  293. for(var i=0; i<opts.fieldTypes.length; i++){
  294. var type = opts.fieldTypes[i];
  295. var field = form.find('.'+type+'-f').not(tmp);
  296. if (field.length && field[type]){
  297. field[type]('clear');
  298. tmp = tmp.add(field);
  299. }
  300. }
  301. form.form('validate');
  302. }
  303. function reset(target){
  304. target.reset();
  305. var form = $(target);
  306. var opts = $.data(target, 'form').options;
  307. for(var i=opts.fieldTypes.length-1; i>=0; i--){
  308. var type = opts.fieldTypes[i];
  309. var field = form.find('.'+type+'-f');
  310. if (field.length && field[type]){
  311. field[type]('reset');
  312. }
  313. }
  314. form.form('validate');
  315. }
  316. /**
  317. * set the form to make it can submit with ajax.
  318. */
  319. function setForm(target){
  320. var options = $.data(target, 'form').options;
  321. $(target).unbind('.form');
  322. if (options.ajax){
  323. $(target).bind('submit.form', function(){
  324. setTimeout(function(){
  325. ajaxSubmit(target, options);
  326. }, 0);
  327. return false;
  328. });
  329. }
  330. $(target).bind('_change.form', function(e, t){
  331. if ($.inArray(t, options.dirtyFields) == -1){
  332. options.dirtyFields.push(t);
  333. }
  334. options.onChange.call(this, t);
  335. }).bind('change.form', function(e){
  336. var t = e.target;
  337. if (!$(t).hasClass('textbox-text')){
  338. if ($.inArray(t, options.dirtyFields) == -1){
  339. options.dirtyFields.push(t);
  340. }
  341. options.onChange.call(this, t);
  342. }
  343. });
  344. setValidation(target, options.novalidate);
  345. }
  346. function initForm(target, options){
  347. options = options || {};
  348. var state = $.data(target, 'form');
  349. if (state){
  350. $.extend(state.options, options);
  351. } else {
  352. $.data(target, 'form', {
  353. options: $.extend({}, $.fn.form.defaults, $.fn.form.parseOptions(target), options)
  354. });
  355. }
  356. }
  357. function validate(target){
  358. if ($.fn.validatebox){
  359. var t = $(target);
  360. t.find('.validatebox-text:not(:disabled)').validatebox('validate');
  361. var invalidbox = t.find('.validatebox-invalid');
  362. invalidbox.filter(':not(:disabled):first').focus();
  363. return invalidbox.length == 0;
  364. }
  365. return true;
  366. }
  367. function setValidation(target, novalidate){
  368. var opts = $.data(target, 'form').options;
  369. opts.novalidate = novalidate;
  370. $(target).find('.validatebox-text:not(:disabled)').validatebox(novalidate ? 'disableValidation' : 'enableValidation');
  371. }
  372. $.fn.form = function(options, param){
  373. if (typeof options == 'string'){
  374. this.each(function(){
  375. initForm(this);
  376. });
  377. return $.fn.form.methods[options](this, param);
  378. }
  379. return this.each(function(){
  380. initForm(this, options);
  381. setForm(this);
  382. });
  383. };
  384. $.fn.form.methods = {
  385. options: function(jq){
  386. return $.data(jq[0], 'form').options;
  387. },
  388. submit: function(jq, options){
  389. return jq.each(function(){
  390. ajaxSubmit(this, options);
  391. });
  392. },
  393. load: function(jq, data){
  394. return jq.each(function(){
  395. load(this, data);
  396. });
  397. },
  398. clear: function(jq){
  399. return jq.each(function(){
  400. clear(this);
  401. });
  402. },
  403. reset: function(jq){
  404. return jq.each(function(){
  405. reset(this);
  406. });
  407. },
  408. validate: function(jq){
  409. return validate(jq[0]);
  410. },
  411. disableValidation: function(jq){
  412. return jq.each(function(){
  413. setValidation(this, true);
  414. });
  415. },
  416. enableValidation: function(jq){
  417. return jq.each(function(){
  418. setValidation(this, false);
  419. });
  420. },
  421. resetValidation: function(jq){
  422. return jq.each(function(){
  423. $(this).find('.validatebox-text:not(:disabled)').validatebox('resetValidation');
  424. });
  425. },
  426. resetDirty: function(jq){
  427. return jq.each(function(){
  428. $(this).form('options').dirtyFields = [];
  429. });
  430. }
  431. };
  432. $.fn.form.parseOptions = function(target){
  433. var t = $(target);
  434. return $.extend({}, $.parser.parseOptions(target, [
  435. {ajax:'boolean',dirty:'boolean'}
  436. ]), {
  437. url: (t.attr('action') ? t.attr('action') : undefined)
  438. });
  439. };
  440. $.fn.form.defaults = {
  441. fieldTypes: ['tagbox','combobox','combotree','combogrid','combotreegrid','datetimebox','datebox','combo',
  442. 'datetimespinner','timespinner','numberspinner','spinner',
  443. 'slider','searchbox','numberbox','passwordbox','filebox','textbox','switchbutton'],
  444. novalidate: false,
  445. ajax: true,
  446. iframe: true,
  447. dirty: false,
  448. dirtyFields: [],
  449. url: null,
  450. queryParams: {},
  451. onSubmit: function(param){return $(this).form('validate');},
  452. onProgress: function(percent){},
  453. success: function(data){},
  454. onBeforeLoad: function(param){},
  455. onLoadSuccess: function(data){},
  456. onLoadError: function(){},
  457. onChange: function(target){}
  458. };
  459. })(jQuery);