2014-07-15 60 views
-4

我有四個複選框。我需要檢查是否選擇了至少2個。他們不在任何DIV內部。他們是獨立的。僅當選擇至少2個複選框時纔會提交表格。jQuery複選框計數選擇

+0

請張貼的HTML片段,以及顯示你已經嘗試過jQuery的片段。 – Brian

+0

'$('。checkboxes:checked')。length> 1' – adeneo

+0

還有其他部分也有複選框,所以不能直接使用它。 –

回答

0

請嘗試此代碼。

<form id="submitForm" method="POST"> 

<input type="checkbox" name="checkboxname" id="checkboxname" value="check1"> check1 
<input type="checkbox" name="checkboxname" id="checkboxname" value="check2"> check2 
<input type="checkbox" name="checkboxname" id="checkboxname" value="check3"> check3 
<input type="checkbox" name="checkboxname" id="checkboxname" value="check4"> check4 

<input type="submit" name="proceed" value="proceed" id="proceed"> 
</form> 

和jQuery腳本是

$(document).ready(function(){ 
    $('#proceed').click(function(){ 
     alert('im triggered') 
     alert($('#checkboxname:checked').length) 
    }); 

}); 

試試吧。

+0

亞洲感謝噸似乎工作:) –

0

完整代碼:

<!DOCTYPE> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <title>jQuery Playground</title> 
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 
</head> 

<body> 
    <h1>Submit Form</h1> 
    <p>Select two options below and submit form</p> 
    <form action="action.php" method="post" id="myForm" enctype="application/x-www-form-urlencoded"> 
     <p>Select only 2 fruits you would like to have for dinner</p> 
     <input type="checkbox" name="fruit" value="orange" class="fruit"> Oranges<br> 
     <input type="checkbox" name="fruit" value="banana" class="fruit"> Bananas<br> 
     <input type="checkbox" name="fruit" value="apple" class="fruit"> Apples<br> 
     <input type="checkbox" name="fruit" value="grape" class="fruit"> Grape<br> 
     <input id="go" type="submit" value="Go Button"> 
    </form> 
    <script> 
     jQuery(function($){ 

      $("#myForm").on("submit", function(e){ 

       // check if 2 items have been checked      
       if($(".fruit:checked").length !== 2){ 
        e.preventDefault(); 
        return false; 
       } 
       // continue form submission if 2 items have been checked 
      }); 
     }); 

    </script> 
</body>