Sprawdź czy pole wyboru jest zaznaczone jQuery
Jak mogę sprawdzić, czy pole wyboru w tablicy pól wyboru jest zaznaczone przy użyciu id tablicy pól wyboru?
Używam poniższego kodu, ale zawsze zwraca liczbę zaznaczonych checkboxów niezależnie od id.
function isCheckedById(id) {
alert(id);
var checked = $("input[@id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
23 answers
Identyfikatory muszą być unikalne w Twoim dokumencie, co oznacza, że nie powinieneś robić tego:
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
Zamiast tego upuść ID, a następnie wybierz je po nazwie lub po elemencie zawierającym:
<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
A teraz jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-31 08:41:36
$('#' + id).is(":checked")
To dostaje, jeśli pole wyboru jest zaznaczone.
Dla tablicy checkboxów o tej samej nazwie można uzyskać listę sprawdzonych przez:
var $boxes = $('input[name=thename]:checked');
Następnie przejrzyj je i zobacz, co możesz zrobić:
$boxes.each(function(){
// Do stuff here with this
});
Aby dowiedzieć się, ile jest sprawdzanych, możesz zrobić:
$boxes.length;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-18 14:03:34
$('#checkbox').is(':checked');
Powyższy kod zwraca true, jeśli pole wyboru jest zaznaczone lub false, jeśli nie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-18 14:49:30
Użyteczne są wszystkie następujące metody:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked
Zaleca się, aby DOMelement lub inline " to.zaznaczone " należy unikać zamiast metody jQuery on Zastosować detektor zdarzeń.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-13 16:25:18
Kod JQuery do sprawdzenia czy pole jest zaznaczone czy nie:
if($('input[name="checkBoxName"]').is(':checked'))
{
// checked
}else
{
// unchecked
}
Alternatywnie:
if($('input[name="checkBoxName"]:checked'))
{
// checked
}else{
// unchecked
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-08 21:06:32
Najważniejszą koncepcją do zapamiętania o sprawdzonym atrybucie jest że nie odpowiada sprawdzonej właściwości. Atrybut faktycznie odpowiada właściwości defaultChecked i powinien być używany tylko, aby ustawić wartość początkową pola wyboru. Atrybut sprawdzony wartość nie zmienia się wraz ze stanem pola wyboru, podczas gdy sprawdzona nieruchomość tak. W związku z tym, cross-browser-compatible sposób na określ, czy pole wyboru jest zaznaczone, aby użyć własność
Wszystkie poniższe metody są możliwe
elem.checked
$(elem).prop("checked")
$(elem).is(":checked")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-09 06:40:32
Możesz użyć tego kodu,
if($("#checkboxId").is(':checked')){
// Code in the case checkbox is checked.
} else {
// Code in the case checkbox is NOT checked.
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-03 04:22:36
Jest to również pomysł, z którego często korzystam:
var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;
Jeśli checked, zwróci 1; w przeciwnym razie zwróci 0.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-08 18:52:59
Zgodnie z dokumentacją jQuery istnieją następujące sposoby sprawdzenia, czy pole wyboru jest zaznaczone, czy nie. Rozważmy na przykład pole wyboru (sprawdź działanie jsfiddle z wszystkimi przykładami)
<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />
Przykład 1-z zaznaczonym
$("#test-with-checked").on("click", function(){
if(mycheckbox.checked) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Przykład 2-With jQuery is, NOTE -: checked
var check;
$("#test-with-is").on("click", function(){
check = $("#mycheckbox").is(":checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Przykład 3-z jQuery prop
var check;
$("#test-with-prop").on("click", function(){
check = $("#mycheckbox").prop("checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Sprawdź działanie jsfiddle
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-28 05:31:11
Możesz spróbować tego:
<script>
function checkAllCheckBox(value)
{
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
}
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 13:09:56
Wiem, że OP chce jquery, ale w moim przypadku pure JS było odpowiedzią, więc jeśli ktoś taki jak ja jest tutaj i nie ma jquery lub nie chce go używać - oto odpowiedź JS:
document.getElementById("myCheck").checked
Zwraca true, jeśli wejście o ID myCheck jest zaznaczone i false, jeśli nie jest zaznaczone.
To proste.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-28 09:52:37
Możesz użyć dowolnego z poniższych kodów zalecanych przez jquery.
if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-17 13:02:31
Można to zrobić po prostu jak;
HTML
<input id="checkbox" type="checkbox" />
JQuery
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
Lub nawet prościej;
$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");
Jeśli checkbox
jest zaznaczone zwróci true
w przeciwnym razie undefined
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-08 12:24:29
Proste Demo do sprawdzania i ustawiania pola wyboru.
Jsfiddle !
$('.attr-value-name').click(function() {
if($(this).parent().find('input[type="checkbox"]').is(':checked'))
{
$(this).parent().find('input[type="checkbox"]').prop('checked', false);
}
else
{
$(this).parent().find('input[type="checkbox"]').prop('checked', true);
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 13:12:43
Powiem tylko, że w moim przykładzie sytuacja była oknem dialogowym, które następnie zweryfikowało pole wyboru przed zamknięciem okna dialogowego. Żaden z powyższych oraz Jak sprawdzić czy checkbox jest zaznaczony w jQuery? i jQuery jeśli pole wyboru jest zaznaczone również nie działa.
Na końcu
<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">
var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');
To zadziałało, więc wywołanie klasy potem ID. a nie tylko dowód osobisty. Może to być spowodowane zagnieżdżonymi elementami DOM na tej stronie powodującymi problem. Obejście było powyżej.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:32
Dla checkboxa o id
<input id="id_input_checkbox13" type="checkbox"></input>
Możesz po prostu zrobić
$("#id_input_checkbox13").prop('checked')
Otrzymasz true
lub false
jako wartość zwracaną dla powyższej składni. Można go użyć w klauzuli if jako zwykłego wyrażenia boolowskiego.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-05 13:19:14
Coś takiego może pomóc
togglecheckBoxs = function( objCheckBox ) {
var boolAllChecked = true;
if( false == objCheckBox.checked ) {
$('#checkAll').prop( 'checked',false );
} else {
$( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
if( false == chkbox.checked ) {
$('#checkAll').prop( 'checked',false );
boolAllChecked = false;
}
});
if( true == boolAllChecked ) {
$('#checkAll').prop( 'checked',true );
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-30 03:24:40
Właściwie, według jsperf.com , operacje DOM są najszybsze, następnie $().prop () po którym następuje $(). is ()!!
Oto składnia:
var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
/* The DOM way - The fastest */
if(checkbox[0].checked == true)
alert('Checkbox is checked!!');
/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
alert('Checkbox is checked!!');
/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
alert('Checkbox is checked!!');
Ja osobiście wolę .prop()
. W przeciwieństwie do .is()
, może być również używany do ustawiania wartości.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-10 17:13:58
Przełącz pole wyboru zaznaczone
$("#checkall").click(function(){
$("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-08 05:15:40
Używając tego kodu możesz zaznaczyć co najmniej jedno pole wyboru jest zaznaczone lub nie w różnych grupach pól wyboru lub z wielu pól wyboru. Dzięki temu nie można wymagać usuwania identyfikatorów ani identyfikatorów dynamicznych. Ten kod działa z tymi samymi identyfikatorami.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-26 13:07:56
Twoje pytanie nie jest jasne: chcesz podać "checkbox array id" na wejściu i uzyskać true/false
na wyjściu - w ten sposób nie będziesz wiedział, które pole zostało zaznaczone (jak sugeruje nazwa funkcji). Poniżej znajduje się moja propozycja ciała twojego isCheckedById
, które na wejściu weź checkbox id
i na wyjściu return true/false
(to bardzo proste, ale twoje ID nie powinno być słowem kluczowym),
this[id].checked
function isCheckedById(id) {
return this[id].checked;
}
// TEST
function check() {
console.clear()
console.log('1',isCheckedById("myCheckbox1"));
console.log('2',isCheckedById("myCheckbox2"));
console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-20 07:58:39
Ponieważ jest połowa 2019 roku, a jQuery czasami zajmuje tylne siedzenie Do Rzeczy Takich jak VueJS, React itp. Oto opcja pure vanilla Javascript onload listener:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-05 13:38:10
Użyj kodu poniżej
<script>
$(document).ready(function () {
$("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}
function ShowMailSection() {
if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
$("[id$='SecEmail']").removeClass("Hide");
}
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-27 06:37:42