簡體   English   中英

JQuery獲取復選框選中狀態

[英]Get checkbox selected state with JQuery

我嘗試了很多方法來獲取復選框的選中狀態。 它是一個帶有類型復選框的輸入字段。

我嘗試了以下方法來獲取狀態,但都返回false 僅當之前使用 jQuery 將復選框設置為選中/未選中(這是通過$.prop("checked", "true")完成的。

$("#ID").prop("checked");
$("#ID").val(); //returns "on" everytime
$("#ID").attr("checked");
$("#ID").checked; //undefined

ID 在我的代碼中是一個真實的 id!

選定狀態也使用 jQuery 設置,如下所示:

$(columns[i]).children().first().prop("checked", stateArray[i]);

復選框位於 KendoGrid 中,columns.children 獲取所有td並且first()返回輸入。

stateArray是一個有 true/false 的數組。

什么都行不通……你有主意嗎?

問候

編輯:我發現了錯誤......為輸入生成的 ID 總是相同的......所以它選擇了第一個未被選中的元素......我很抱歉!

您的選擇器在哪里? 如下使用is(":checked")

var status = $(':checkbox').is(":checked");

要查找復選框是否選中,請使用$('input[type="checkbox"]').prop("checked")

要了解更多信息,請查看以下代碼段。

 $('input[type="checkbox"]').on('change',function(){ if($(this).prop('checked')){ alert("checked"); }else{ alert("un-checked"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox"/> 

您需要首先從DOM選中checkbox ,然后讀取其checked屬性。

 $(function() { console.log($('#ab3fee6b-c81e-e4ba-b12e-2c088bb386cc_A4').prop('checked')); console.log($('#ab3fee6b-c81e-e4ba-b12e-2c088bb386cc_A5').prop('checked')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="ab3fee6b-c81e-e4ba-b12e-2c088bb386cc_A4" type="checkbox" data-role="check" otg-visible="true" style="-webkit-appearance: checkbox !important; width: 20px; height: 20px; display: table-cell; margin: 0px;"> <input id="ab3fee6b-c81e-e4ba-b12e-2c088bb386cc_A5" type="checkbox" data-role="check" checked otg-visible="true" style="-webkit-appearance: checkbox !important; width: 20px; height: 20px; display: table-cell; margin: 0px;"> 

您可以嘗試以下任一方法:

$('#checkbox_id').is(":checked"); // jQuery

document.getElementById("checkbox_id").checked //JavaScript

如果checkbox被選中,則返回true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM