Laziale
Laziale

Reputation: 8225

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:

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

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

//I want to put the checkbox logic here

Thanks again

Upvotes: 10

Views: 26520

Answers (5)

Sulaiman Zahir
Sulaiman Zahir

Reputation: 1

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

Upvotes: 0

end1dream
end1dream

Reputation: 131

Add a data attribute to your checkbox and use the 'hasClass' function jQuery provides. Like below:

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

Upvotes: 0

mccrager
mccrager

Reputation: 1038

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.

The id of the checkbox isn't going to be checkboxRules as you have it in the source code. 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.

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".

$('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.

Upvotes: 4

Suave Nti
Suave Nti

Reputation: 3739

try...

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

Upvotes: 12

Anders Abel
Anders Abel

Reputation: 69250

Assuming your checkbox is the only item on the page having the checkbox class:

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

Upvotes: 3

Related Questions