2015-10-01 79 views
2

我有兩個具有相同類名的表單。我想檢查點擊的所有必填字段。 HTML:每個這個對象內使用jquery

<form action="#" id="form_sample_3" class="form-horizontal normalForm1"> 
      <div class="form-group c_name_container"> 
       <div class="col-md-12"> 
        <div class="input-group"> 
         <span class="input-group-addon"> 
          <i class="fa fa-envelope"></i> 
         </span> 
         <input type="text" id="c_name" class="required" placeholder="Type your Name here"/> 
        </div> 
       </div> 
      </div> 
      <div class="form-group c_email_container"> 
       <div class="col-md-12"> 
        <div class="input-group"> 
         <span class="input-group-addon"> 
          <i class="fa fa-envelope"></i> 
         </span> 
         <input type="email" id="c_email" class="required" placeholder="Type your Email Address"> 
        </div> 
       </div> 
      </div> 
      <div class="form-actions"> 
       <div class="row"> 
        <div class="col-md-offset-3 col-md-9"> 
         <button type="button" id="start_chat" class="btn green">Start Chat</button> 
        </div> 
       </div> 
      </div> 
     </form> 

現在,

$(document).on("click", ".normalForm button[type='submit']", function() { 
    // this will refer clicked form having class `normalForm` 
    // Here i want to looping for all .required class. 
    $('.required').each(function(){ 
     // it works fine. but it looping also others .required class of other form in same page. How can I looping only inside my clicked form? 


     }); 
}); 
+0

'$( '#form_sample_3 .required')每個(函數(){...' – ojovirtual

+0

@ojovirtual ** **沒有!!!!他希望它在_current_表格上參數化,而不是硬編碼的! – Alnitak

回答

2

您應該綁定submit事件form而不是點擊提交按鈕即可提交form。然後,只需這form內循環對所有.required要素:

$(document).on('submit', '.normalForm', function() { 
    $(this).find('.required').each(function() { 
     /*...*/ 
    }); 
}); 
+1

很好的一點關於在表單上代替「點擊」扣除「提交」 - 這應該是公認的答案! – Alnitak

1

試試這個:

$('.required', this.form).each(function() { 
    ... 
}; 
+0

另外'$(this.form).find('。required')。each(function(){...});' –

1

我會用:

$(this).closest('form').find('.required').each(...) 

因爲this將點擊的按鈕,而不是形式本身,而this.form是僅HTML5。