2014-03-03 42 views
0
<input type="checkbox" value="On" name="policy" id="policy"></font> 
    <b><font face="Verdana" color="#ff0000" size="1">*</font></b>By checking the box, you are verifying with your digital signature that you have read and agree to all terms and conditions of the <a href="Anico_2013-08-26.pdf" target="_blank">FEG agent agreement</a>. 
    </td> 
</tr> 
<tr class="gr"> 
    <td class="rowdot_lno">Do you agree?:</td> 
    <td class="rowdot_lno"> 
    <input type="checkbox" value="On" name="iagree" id="iagree"> 
    <b><font face="Verdana" color="#ff0000" size="1">*</font></b>I understand that I will be charged $24.95. 
    </td> 
</tr> 

我前必須檢查需要兩個複選框具有<form method="post" action="enroller.dhtml" name="mainform" onSubmit="update_prices()">和一個按鈕<input type="submit" value="Continue">我有表格可提交

我已經嘗試了一些東西,但無濟於事。可以提交表單而不檢查複選框。這裏是我嘗試過的最新版本的jQuery。

$('input[type=checkbox]').each(function() { 
     if($(this).is(':checked')) { 
      return true; 
     } 
    }); 
    alert("Please select at least one to upgrade."); 
    return false; 
}); 

此外,我發現這在小提琴,但它不是真的工作..我試圖定製它,以滿足我的需求。

http://jsfiddle.net/shryme/D3Ldj/

+2

您在關聯的jsfiddle似乎是工作,是一個完全不同的事情 –

+0

到底是什麼不行?即使未檢查兩個框,表單是否也會提交? – Sebsemillia

+0

是表單提交時沒有檢查這些框。 –

回答

1

如果您對您的提交按鈕或添加它雖然jQuery的一個的onsubmit,調用一個函數,它會:

if ($('input[type=checkbox] :checked').length == 0) { 
    alert("Please select at least one to upgrade."); 
    return false; 
} else { return true; } 

我希望這是你在找什麼。

0

我會建議用一些MVVM框架來做,但這裏有一些代碼可以用jQuery來做到這一點。我這樣做是爲了使提交按鈕被禁用,除非這兩個框被選中。

Fiddle with 2 checkboxes and a submit button

function areChecked(){ 
    var is_1_checked = $('#check_1').is(':checked'); 
    var is_2_checked = $('#check_2').is(':checked'); 

    return is_1_checked == is_2_checked == true; 
} 

function enableButton(val){ 
    $('#submit').attr('disabled', false); 
} 

$('#check_1').on('click', function(){ 
    if (areChecked()) 
    enableButton(false); 
}); 

$('#check_2').on('click', function(){ 
    if (areChecked()) 
    enableButton(false); 
}); 
0

從這一行:

請選擇至少一個升級

看來你至少需要一個複選框選中。如果是這樣的話,你可以做這樣的事情:

$("form").submit(function(){ 
    var length = $("input[type=checkbox]").not(":checked").length; 
    if (length > 1) { 
     alert("Please select at least one to upgrade."); 
     return false; 
    } 
}); 

進行檢查,看看有多少複選框不檢查,確定該數量小於所需數量,如果是,觸發錯誤信息。

您還可以進一步簡化length變量,如果您熟悉CSS選擇器:

var length = $("input[type=checkbox]:not(:checked)").length; 

Here's an example.