简体   繁体   English

jquery 检查是否选中了 asp 复选框

[英]jquery check if asp checkbox is checked

Hello everyone I have a checkbox I want to check if its checked or no on client side, before postback happens.大家好,我有一个复选框,我想在回发发生之前在客户端检查它是否已选中。 Here is the checkbox:这是复选框:

 <asp:CheckBox runat="server" CssClass="checkbox" Checked="true" ID="checkboxRules" />

Thanks in advance, Laziale提前致谢, 拉齐亚莱

UPDATE: The problem is that there is a button on the page too which is triggered by js code, and maybe I can add a line there to check if the checkbox is checked once the button is clicked, otherwise display message for unchecked checkbox:更新:问题是页面上也有一个由 js 代码触发的按钮,也许我可以在那里添加一行来检查单击按钮后复选框是否被选中,否则显示未选中复选框的消息:

function enterClick() { $('#SUBMIT').click();函数 enterClick() { $('#SUBMIT').click(); } }

var ishown = false;
$(document).ready(function () {
    $('#BUTTON').click(function (e) {

//I want to put the checkbox logic here //我想把复选框逻辑放在这里

Thanks again再次感谢

try...尝试...

if ($('#<%= checkboxRules.ClientID %>').is(':checked')) {
...
}

Since it is a server-side Checkbox, it will send something like <input type="checkbox" class="checkbox" /> as HTML to the client after ASP.NET processes the control.由于它是一个服务器端 Checkbox,它会在 ASP.NET 处理控件后将类似<input type="checkbox" class="checkbox" />的内容作为 HTML 发送到客户端。

The id of the checkbox isn't going to be checkboxRules as you have it in the source code.复选框的 id 不会像您在源代码中那样成为 checkboxRules 。 ASP.NET will make a concatenation of the server-side form id + master page id (if using a master page) + checkboxRules so in this case I won't use a selector that depends on element id. ASP.NET 将连接服务器端表单 ID + 母版页 ID(如果使用母版页)+ checkboxRules,因此在这种情况下我不会使用依赖于元素 ID 的选择器。

We can make a jQuery selector as narrow as possible to only select inputs with a type of "checkbox" and with a CSS class of "checkbox".我们可以使 jQuery 选择器尽可能窄,以仅选择具有“复选框”类型和 CSS 类“复选框”的输入。

$('input[type=checkbox] .checkbox').attr('checked')

will return the boolean value of the check status of the input.将返回输入检查状态的布尔值。 This will find any input on the page that is a checkbox with that CSS class.这将在页面上找到任何带有该 CSS 类的复选框的输入。

Assuming your checkbox is the only item on the page having the checkbox class:假设您的复选框是页面上唯一具有复选框类的项目:

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

Add a data attribute to your checkbox and use the 'hasClass' function jQuery provides.将数据属性添加到您的复选框并使用 jQuery 提供的“hasClass”函数。 Like below:像下面这样:

 var isChecked = $('[data-checkbox]').hasClass('checkbox-selected');
 <asp:CheckBox data-checkbox="" Text="Some Caption" runat="server" />

if($("[id$='checkbox_ID']").prop('checked')) //Result: true or false
{
 // your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM