Brent Oliver Brent Oliver - 2 months ago 19
ASP.NET (C#) Question

Enable button using checkbox

I see a couple old/er posts on this when I search, but for whatever reason I cannot get any of the code examples to work in my project.

I want to use a checkbox control to enable/disable a submit button so that users have to agree to use terms before being able to register.

Using SQL Server backend, asp.net and C#. I would prefer to use javascript to do this enabling/disabling, but open to anything that works.

At this point I have dropped all attempts for the actual code and hoping someone can assist to come up with something that will work (hence why no javascript below).

asp.net controls:

<div>
<asp:CheckBox ID="checkbox1" runat="server" Text="I Agree" Checked="false" />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" ID="btnRegister" OnClick="CreateUser_Click" Text="Register" CssClass="btn btn-default" Enabled="false"/>
</div>
</div>


Update 8/5/2016 - I have tried the code in the item that is indicated by multiple people as a duplicate, and it does not work. In the question submitted the checkbox is an HTML item, not asp.net, and the button is not referenced at all. I have tried to change that code around to fit, but nothing is occurring with the button when I check/uncheck the checkbox.

Able to use the below Javascript to do the desired function:


$(function () {
var $btn = $(":submit[id$=btnRegister]");
var $chk = $(":input:CheckBox[id$=checkbox1]");
// check on page load
checkChecked($chk);
$chk.click(function () {
checkChecked($chk);
});
function checkChecked(chkBox) {
if ($chk.is(':checked')) {
$btn.removeAttr('disabled');
}
else {
$btn.attr('disabled', 'disabled')
}
}
});



Answer

Used the below Javascript:

<script type="text/javascript" > $(function () { var $btn = $(":submit[id$=btnRegister]"); 
var $chk = $(":input:CheckBox[id$=checkbox1]"); 
// check on page load checkChecked($chk); $chk.click(function () { checkChecked($chk); });
 function checkChecked(chkBox) { if ($chk.is(':checked')) { $btn.removeAttr('disabled'); } 
else { $btn.attr('disabled', 'disabled') } } }); 
</script> 
Comments