[英]Check if specific checkboxes are checked
我有一個帶有多個復選框的表單,如下所示:
<form id="myForm">
<input type="checkbox" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" id="third" />
</form>
我僅在選擇復選框1和3時才想做某事(即警報框)。
我知道如何定位一個復選框,如下所示:
$('#first').click(function () {
if ($(this).prop("checked") == true) {
alert("I'm checked!");
}
});
但是有沒有辦法針對特定的多個復選框呢?
此答案的前提是您希望選中兩個指定復選框中的任何一個,而不是同時選中兩個指定復選框,而可以使用兩個逗號分隔的選擇器來完成:
$('#first, #third')
或通過使用類名來標識相關元素:
$('.alertIfSelectedClassName')
使用以下HTML:
<form id="myForm">
<input type="checkbox" class="alertIfSelectedClassName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" class="alertIfSelectedClassName" id="third" />
</form>
基於共享屬性(例如<input>
的名稱)使用CSS屬性選擇:
$('input[name=alertIfSelectedElementName')
HTML:
<form id="myForm">
<input type="checkbox" name="alertIfSelectedElementName" id="first" />
<input type="checkbox" id="second" />
<input type="checkbox" name="alertIfSelectedElementName" id="third" />
</form>
您可以遍歷它們:
<form id="myForm">
<input type="checkbox" name="somename" id="first" />
<input type="checkbox" name="somename" id="second" />
<input type="checkbox" name="somename" id="third" />
</form>
$('checkbox[name=somename"]').each(function () {
if ($(this).prop("checked") == true) {
alert("I'm checked!");
}
});
嘗試這個:
$('#first, #third').click(function () {
var firstChecked = $('#first).prop("checked") == true);
var thirdChecked = $('#third).prop("checked") == true);
if (firstChecked && thirdChecked ) {
alert("I'm checked!");
}
})
https://jsfiddle.net/p1zjaw46/
var $toCheck = $('#first').add('#third');
$(function () {
$('input[type="checkbox"]').on('change', function () {
if ( $toCheck.filter(':checked').length === $toCheck.length )
alert('good');
else
alert('bad');
})
});
基本上:
$toCheck
在這種情況下。 ":checked"
進行filter
,並將filter
結果的長度與原始復選框的長度進行比較。 如果它們不相等,則不會選中至少一個預期的框!
您需要做的就是將新元素添加到$toCheck
,其余的都是自動的
您可以使用is(':checked')
來檢查復選框是否已選中,也可以使用&&
符號檢查示例來檢查是否都選中了復選框。
希望這可以幫助。
$("#first, #third").click(function () { if ($('#first').is(':checked') && $('#third').is(':checked')) { alert("Message!"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myForm"> <input type="checkbox" id="first" /> <input type="checkbox" id="second" /> <input type="checkbox" id="third" /> </form>
為了定位特定元素,請嘗試使用css
類作為選擇器。 另外,包括輸入type
以使您與具有相同類的其他元素沒有任何沖突。 為了檢查是否選中了所有必需的復選框,可以使用.each()
循環並確定是否都選中了這些復選框,並基於顯示的alert()
來確定它們。 以下方法避免了任何硬編碼和multiple if
檢查。
$("input:checkbox.test").click(function()
{
var allchecked = true;
$("input:checkbox.test").each(function(){
if(!$(this).is(":checked"))
allchecked = false;
});
if(allchecked)
alert("Im checked");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.