Reputation: 15807
I have an asp.net checkbox, which looks like this:
<asp:CheckBox ID="chkDoSomething" runat="server" AutoPostBack="true" OnCheckedChanged="DoSomething" />
As expected when I check the checkbox; the DoSomething
method is called on the server side. After the user has checked the checkbox; I want to disable it (so they cannot click it multiple times).
If I was using a button, then I could use OnClick and OnClientClick. How can I do this with a Checkbox?
I have spent one hour Googling this and have looked here for example: Enabling/disabling asp.net checkboxes through javascript
I cannot find an answer to my question. Most questions I have read assume that you want to execute Javascript only and not both Javascript and server side code.
Update 1
Here is the onchange method:
function Disable
Checkbox()
{
document.getElementById("chkDoSomething").disabled = true;
}
Update 2
I have tried this:
var chkDoSomething = document.getElementById("chkDoSomething");
if (chkDoSomething != null) {
chkDoSomething.addEventListener('change', function () {
chkDoSomething.disabled = true;
});
}
Still the Javascript blocks the post back. As soon as I remove the Javascript, then the postback works.
Upvotes: 1
Views: 2872
Reputation: 61904
This is the same client-side solution as VDWWD's answer but written using native JS instead of jQuery, as you requested:
<script>
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("change", function() {
let div = this.closest("div");
div.style.pointerEvents = "none";
});
}
</script>
As noted, this requires each affected checkbox to be wrapped inside a <div>
.
Upvotes: 2
Reputation: 35514
You can also disable the CheckBox in the CheckedChanged
event.
protected void chkDoSomething_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = sender as CheckBox;
cb.Enabled = false;
}
Update
A client side solution would be to wrap the CheckBox in a div and add pointer-events:none
to it.
<div>
<asp:CheckBox ID="chkDoSomething" runat="server"/>
</div>
<script>
$('input[type="checkbox"]').change(function () {
$(this).closest('div').css('pointer-events', 'none');
});
</script>
Upvotes: 2