// // フォーム入力状態管理 // var ev = new FormEvents({ category:'xxx' }); // var FormEvents = (function(){ 'use strict'; var jsClass = function( arg ){ // コンストラクタ this.Category = arg.category || '?'; // GAイベントカテゴリー this.Action = 'input'; // GAイベントアクション this.errors = []; // サーバーエラー項目ID配列 this.enters = []; // 入力完了項目ID配列 this.lastFocus = ''; // 最後にfocusしたフォーム項目 var self = this; // サーバーエラー取得 var $error_info = $('#error_info'); $error_info.children('li').each(function(){ self.errors.push( self.fieldID(this) ); }); if( this.errors.length ){ $error_info.css('display','block'); } // イベント記録開始 $('#confirm').on('click',function(){ self.clear(); }); $(document).on('focus','select,input,textarea',function(){ self.focused( this ); }); $(window).on({ beforeunload:function(){ if( self.exists() ) return 'ウインドウを閉じるとこれまで入力した内容が失われます。'; }, unload:function(){ if( self.exists() ) ga('send','event', self.Category, self.Action, self.status() +'away'); } }); }; var p = jsClass.prototype; // イベントが記録されているか(フォーカスイベントは無視) p.exists = function(){ return ( this.errors.length || this.enters.length ); }; // イベントクリア p.clear = function(){ this.errors = this.enters = []; this.lastFocus = ''; }; // 項目1つ入力完了 p.entered = function( element ){ this.enters.push( this.fieldID(element) ); }; // 項目にフォーカス来た p.focused = function( element ){ if( element ) this.lastFocus = this.fieldID(element); }; // これまでの状態テキスト // 例)errors=5 enters=3 focus=xxxx p.status = function(){ var status = ''; // サーバーエラー項目数 if( this.errors.length ) status += 'errors='+ this.errors.length +' '; // validation合格した回数(※項目数でなく回数) if( this.enters.length ) status += 'enters='+ this.enters.length +' '; // 最後にフォーカスした要素ID if( this.lastFocus ) status += 'focus='+ this.lastFocus +' '; return status ? status : '? '; }; p.fieldID = function( element ){ if( element ){ if( element instanceof jQuery ) element = element[0]; if( element.name ){ return element.name; } if( element.id ){ var id = element.id.replace(/_error$/,''); if( id ){ return id; } } } return '?'; }; return jsClass; })();