javascript - 我如何在 jQuery 中檢查複選框是否被選中?
我需要使用 jQuery 檢查複選框的 checked 屬性,並根據該屬性執行某些操作。
例如,如果選中了 age 核取方塊,那麼我需要顯示一個文本框來輸入 age,否則隱藏該文本框。
但以下程式碼預設會回傳 false:
if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
Age is selected
</div>我該如何成功查詢 checked 屬性?
答案#1
我如何成功查詢 checked 屬性?
勾選框 DOM 元素的 checked 屬性會給你該元素的 checked 狀態。
根據你現有的程式碼,你因此可以這樣做:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
不過,有一種更漂亮的方式來做這件事,使用 toggle:
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>答案#2
使用 jQuery 的 is() 函數:
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show(); // checked
else
$("#txtAge").hide(); // unchecked
答案#3
使用 jQuery 1.6 以上版本
<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />
// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true
使用新的屬性方法:
if($('#checkMeOut').prop('checked')) {
// something when checked
} else {
// something else when not
}
答案#4
jQuery 1.6+
$('#isAgeSelected').prop('checked')
jQuery 1.5 及以下版本
$('#isAgeSelected').attr('checked')
任何版本的 jQuery
// Assuming an event handler on a checkbox
if (this.checked)
所有榮譽都歸功於賢。
答案#5
我正在使用這個,這個運作得非常好:
$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");
注意:如果勾選了該核取方塊,它將返回 true,否則返回未定義,因此最好檢查 "TRUE" 值。
答案#6
使用:
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned答案#7
自 jQuery 1.6 起,jQuery.attr() 的行為已經改變,建議使用者不要使用它來取得元素的選取狀態。相反地,您應該使用 jQuery.prop():
$("#txtAge").toggle(
$("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
// Return value changes with checkbox state
);
另外兩個可能性是:
$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
答案#8
這對我有效:
$get("isAgeSelected ").checked == true
其中 isAgeSelected 是控制項的 id。
另外,@karim79 的回答也很有效。我不確定當時測試時我漏看了什麼。
注意,這個答案使用的是 Microsoft Ajax,而不是 jQuery
答案#9
如果你正在使用更新版本的 jQuery,你必須使用 .prop 方法來解決你的問題:
$ ('#isAgeSelected').prop('checked') 如果被選中將返回 true,如果未選中將返回 false。我已經確認過,並且之前也遇到過這個問題。$ ('#isAgeSelected').attr('checked') 和 $ ('#isAgeSelected').is('checked') 返回 undefined,這對這種情況來說不是有效的答案。所以請按照下面的方法操作。
if($('#isAgeSelected').prop('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
答案#10
使用:
<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
if($(this).is(':checked'))
{
var checkedOne=$(this).val()
alert(checkedOne);
// Do some other action
}
})
如果你希望所需的動作只有在勾選方框時才執行,而不是在取消勾選時執行,這會很有幫助。
答案#11
你可以嘗試使用復選框的 change 事件來追蹤 :checked 狀態的變化。
$("#isAgeSelected").on('change', function() {
if ($("#isAgeSelected").is(':checked'))
alert("checked");
else {
alert("unchecked");
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected" />
<div id="txtAge" style="display:none">
Age is selected
</div>答案#12
對於複選框屬性使用 Click 事件處理程序是不可靠的,因為 checked 屬性可能在事件處理程序自身執行期間發生變化!
理想情況下,你會想要將你的程式碼放入一個 change 事件處理器中,因為每次勾選框的值改變時它都會被觸發(無論這是如何改變的)。
$('#isAgeSelected').bind('change', function () {
if ($(this).is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
});
答案#13
我遇到了完全相同的問題。我有一個 ASP.NET 的勾選框
<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />
在 jQuery 代碼中,我使用了以下選擇器來檢查複選框是否被選中,並且它似乎運作得非常順利。
if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
我確定你也可以使用 ID 而不是 CssClass,
if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
我希望這對你有幫助。
答案#14
我相信你可以做到這個:
if ($('#isAgeSelected :checked').size() > 0)
{
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
答案#15
我決定發表一個回答,說明如何在不使用 jQuery 的情況下做完全相同的事情。只是因為我是一個叛逆者。
var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');
// Just because of IE <333
ageCheckbox.onchange = function() {
// Check if the checkbox is checked, and show/hide the text field.
ageInput.hidden = this.checked ? false : true;
};
首先,你通過它們的 ID 獲取這兩個元素。然後,你給複選框的 onchange 事件分配一個函數,該函數檢查複選框是否被選中,並相應地設置年齡文本欄位的 hidden 屬性。在那個例子中使用了三元運算子。
這裡有一個 fiddle 給你測試。
附錄
如果跨瀏覽器相容性是個問題,那麼我建議將 CSS display 屬性設置為 none 和 inline。
elem.style.display = this.checked ? 'inline' : 'none';
較慢但跨瀏覽器兼容。
答案#16
這段程式碼將幫助你
$('#isAgeSelected').click(function(){
console.log(this.checked);
if(this.checked == true) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
});
答案#17
這對我有效:
/* isAgeSelected being id for checkbox */
$("#isAgeSelected").click(function(){
$(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
答案#18
有很多方法可以檢查核取方塊是否被勾選:
使用 jQuery 的方法來檢查
if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))
查看範例或文件:
http://api.jquery.com/attr/
http://api.jquery.com/prop/
答案#19
這是做同一件事的另一種方法:
$(document).ready(function (){
$('#isAgeSelected').click(function() {
// $("#txtAge").toggle(this.checked);
// Using a pure CSS selector
if ($(this.checked)) {
alert('on check 1');
};
// Using jQuery's is() method
if ($(this).is(':checked')) {
alert('on checked 2');
};
// // Using jQuery's filter() method
if ($(this).filter(':checked')) {
alert('on checked 3');
};
});
});<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>答案#20
使用這個:
if ($('input[name="salary_in.Basic"]:checked').length > 0)
如果勾選了核取方塊,長度將大於零。
答案#21
我做這件事的方式是:
if ( $("#checkbox:checked").length ) {
alert("checkbox is checked");
} else {
alert("checkbox is not checked");
}
答案#22
$(selector).attr('checked') !== undefined
如果輸入已被勾選,這會返回 true;如果沒有勾選,則返回 false。
答案#23
你可以使用:
if(document.getElementById('isAgeSelected').checked)
$("#txtAge").show();
else
$("#txtAge").hide();
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
它們兩個都應該可以用。
答案#24
$(document).ready(function() {
$('#agecheckbox').click(function() {
if($(this).is(":checked"))
{
$('#agetextbox').show();
} else {
$('#agetextbox').hide();
}
});
});
答案#25
1) 如果您的 HTML 標記為:
<input type="checkbox" />
使用的屬性:
$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set
如果使用 prop:
$(element).prop("checked"); // Will give you false whether or not initial value is set
2) 如果您的 HTML 標記為:
<input type="checkbox" checked="checked" />// May be like this also checked="true"
使用的屬性:
$(element).attr("checked") // Will return checked whether it is checked="true"
使用的道具:
$(element).prop("checked") // Will return true whether checked="checked"
答案#26
在點擊時對勾選框被勾選或取消勾選進行操作。
$('#customCheck1').click(function() {
if (this.checked) {
console.log('checked');
} else {
console.log('un-checked');
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="customCheck1">編輯:雖然 .checked 屬性可能也會返回其他類型的變數,但 if (boolean == true) 並不是一個好的程式表達方式。
最好改用 .prop("checked")。它只會返回 true 和 false。
答案#27
這個範例是給按鈕的。
試試以下方法:
<input type="button" class="check" id="checkall" value="Check All" /> <input type="button" id="remove" value="Delete" /> <br/>
<input type="checkbox" class="cb-element" value="1" /> Checkbox 1 <br/>
<input type="checkbox" class="cb-element" value="2" /> Checkbox 2 <br/>
<input type="checkbox" class="cb-element" value="3" /> Checkbox 3 <br/>
$('#remove').attr('disabled', 'disabled');
$(document).ready(function() {
$('.cb-element').click(function() {
if($(this).prop('checked'))
{
$('#remove').attr('disabled', false);
}
else
{
$('#remove').attr('disabled', true);
}
});
$('.check:button').click(function()
{
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).data('checked', checked);
if(checked == true)
{
$(this).val('Uncheck All');
$('#remove').attr('disabled', false);
}
else if(checked == false)
{
$(this).val('Check All');
$('#remove').attr('disabled', true);
}
});
});
答案#28
最上面的答案對我沒用。不過這個有用:
<script type="text/javascript">
$(document).ready(function(){
$("#li_13").click(function(){
if($("#agree").attr('checked')){
$("#saveForm").fadeIn();
}
else
{
$("#saveForm").fadeOut();
}
});
});
</script>
基本上,當點擊元素 #li_13 時,它會使用 .attr('checked') 函數檢查元素 #agree(即勾選框)是否已被選中。如果是,則使 #saveForm 元素淡入,如果不是,則使 #saveForm 元素淡出。
答案#29
雖然你已經為你的問題(當 checkbox 被 checked 時顯示 textbox)提出了一個 JavaScript 解決方案,但這個問題可以僅透過 CSS 來解決。採用這種方法,你的表單對於禁用 JavaScript 的使用者也能正常運作。
假設你有以下的 HTML:
<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />
您可以使用以下 CSS 來實現所需的功能:
#show_textbox:not(:checked) + input[type=text] {display:none;}
對於其他情況,你可以考慮適當的 CSS 選擇器。
這裡有一個 Fiddle 來展示這種方法。
答案#30
我正在使用這個:
<input type="checkbox" id="isAgeSelected" value="1" /> <br/>
<input type="textbox" id="txtAge" />
$("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
