2016-09-28 8 views
1

フォーム検証機能を作成していますが、空の入力がない場合、ボタンは2回のクリックで正しく動作します。関数を呼び出すjQuery:ボタンが2回クリックするとフォームが送信されます

function validate(root, animation, error) { 
    $('.button').on('click', function(event) { 
     event.preventDefault() 

     var isEmpty = false, 
      root  = $(root), 
      animation = animation ? animation : 'animation animation-shake', 
      error  = error ? error : 'error'; 

     root.find('form').find('.required').each(function() { 
      if ($(this).val().length == 0) { 
       isEmpty = true; 
       root.addClass(animation); 
       $('.required.error:first').focus(); 
       $(this).addClass(error).on('keydown', function() { 
        $(this).removeClass(error); 
        root.removeClass(animation); 
       }); 
      } 
     }); 

     if (isEmpty) return; 
     $(this).unbind('click'); 
    }); 
} 

コード:

validate('#login-box .box'); 

すべてのアイデアは、コードを改善/短縮する方法についても提案素晴らしいことだ

は、これは私の関数です。

+0

目的とする動作は何ですか? –

+3

'if(isEmpty){...}'ブロック内に 'event.preventDefault()'を設定します。返信文やクリックイベントのバインドを解除する必要はありません –

+1

'error = error || 'error'; '' error = error? 'と同じ仕事をしますか?エラー: 'エラー'; ' – tewathia

答えて

2

あなたの方法は次のようになります。

function validate(root, animation, error) { 
    $('.button').on('click', function(event) { 
     /* event.preventDefault();*/ //<< remove it 
     var isEmpty = false, 
      /*...*/ 
     /*if (isEmpty) return; 
      $(this).unbind('click');*/ //<< remove it 

     // and set at handler bottom 
     if (isEmpty) event.preventDefault(); 
    }); 
} 

のみ、必要な時に行動を提出防ぎます。

0

2回クリックする必要があるため、ボタンの中にボタンをクリックしてバインドしています。 最初にクリックしてクリックイベントをクリックしてから、2回目にクリックしてコードをトリガーします。 クリックイベントをコードから削除します。

+0

これが関数である前であっても、結果は同じでした。 –

+0

ボタンのクリックから 'validate(..)'が呼び出されているところはどこですか? –

+0

@ freedomn-m。私は$( '。button')のclick()がvalidate関数内に追加されていると思います...私が間違っていないかどうか確認してください。 – Developer

関連する問題