JavaScript disabled attribute not the same as Enabled attribute? - javascript

I'm having some weird issues with the disabled attribute of an asp button and JavaScript, probably due to my lack of experience, but anyway...
As I understand from this question/answer, setting the disabled attribute makes the element disabled. Unless you set it like so; element.disabled = false;
So, that's what I do in my code;
<script type="text/javascript">
function CheckOne(inChkBox) {
... irrelevant code goes here ...
var rejectButton = document.getElementById('btnReject');
if (inChkBox.checked) {
rejectButton.disabled = false;
rejectButton.className = 'Enabled';
} else {
rejectButton.disabled = true;
rejectButton.className = 'Disabled';
}
}
</script>
<input type='checkbox' name='chkRejectLineItem' onchange='CheckOne(this);' runat="server"/>
This seems to trigger and work fine (the cssclass changes at the very least...) apart from the fact that my button is still disabled;
<asp:Button ID="btnProjectTimeReject" runat="server" Text="Reject Selected" OnClientClick="LineItemRejectReason();" OnClick="btnProjectTimeReject_Click" Enabled="False" CssClass="Disabled"/>
I know this, because the OnClientClick never gets called (for some reason, the server side code still gets called??). If I set the button to Enabled="True" then everything works as expected.
Is it because I'm using Enabled="True" initially and I should instead use rejectButton.removeAttribute('disabled') in the enable/disable JavaScript?

After a lot of console debugging and googling the same thing different ways, I found the following solution/answer.
var rejectButton = document.getElementById('btnPLReject');
if (inChkBox.checked) {
rejectButton.disabled = false;
rejectButton.className = 'Enabled';
$('#btnPLReject').bind("click", function() { LeaveRejectReason(); });
} else {
rejectButton.disabled = true;
rejectButton.className = 'Disabled';
}
This causes the button to trigger the JavaScript/Client side code AND then the Server side code...where as it was only doing the Server side code before...
I need some panadol now.

Related

How do I disable an asp:CheckBox after it is checked and then execute server side code?

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

Problem with enabling and disabling button control based on the asp.net check box check

Hi friends i have a button control which has to be enabled based on my asp.net checkbox check,but when run the code i am facing the problem my button is still disabled even after i perform a checkbox check .is their any property i have set in code behind to acccess the check event.
I am using the following code in my application
This is my javascript file
<script type="text/javascript">
function theChecker() {
var checkboxId = '<%= SpEligible.ClientID %>';
alert(checkboxId);
if (checkboxId.checked == true)
{
document.getElementById("SplistButton").disabled = false;
}
else
{
document.getElementById("SplistButton").disabled = true;
}
}
</script>
This is my code for the checkbox and button is
<asp:CheckBox ID="SpEligible" runat="server" Text="SpEligible" class="cBox" />
<asp:Button ID="SplistButton" runat="server" OnClientClick=" return ShowInsertForm()" Enabled="false"/>
This is my aspx.cs file where i am calling the javascript
SpEligible.Attributes.Add("onclick", "theChecker()");
I can see two major errors in your code :
1- In your <script> tag, you did realize that your Checkbox wouldn't have the same ID once in the page, but you didn't made that check. Also, as Ken Pespisa mentioned, the ID you took is only a string, therefore, it doesn't know any checked property. Here is the code I would write :
<script type="text/javascript">
function theChecker() {
var checkboxId = '<%= SpEligible.ClientID %>';
alert(checkboxId);
if (document.getElementById(checkboxId).checked == true)
{
document.getElementById("<%= SplistButton.ClientID %>").disabled = false;
}
else
{
document.getElementById("<%= SplistButton.ClientID %>").disabled = true;
}
}
</script>
2- In your .cs page, you don't seem to use any namespace. You may have hide some code, so I'll just say be sure to have namspaces and be sure to use this line inside a function, maybe the page load event function.
You need to change the javascript code to:
<script type="text/javascript">
function theChecker() {
var checkboxId = document.getElementById('<%= SpEligible.ClientID %>');
alert(checkboxId);
if (checkboxId.checked == true)
{
document.getElementById("SplistButton").disabled = false;
}
else
{
document.getElementById("SplistButton").disabled = true;
}
}
</script>
You were checking the checked property of a string constant. You need to get the control itself using document.getElementById which has checked property. I'd also rename "checkboxId" to "checkbox"
Change
document.getElementById("SplistButton")
to
document.getElementById(checkboxId)

Stop ModalPopupExtender from coming up due to JavaScript

ASP.net project using ajax (.net 2.0).
I've got a modalpopupextender that is linked to an image button:
<asp:ImageButton ID="ibStartNow" runat="server" ImageUrl="images/StartNow.gif"
ToolTip="Save expense report header and start now!" CausesValidation="False"
OnClientClick="CheckReason(); NoPrompt();" />
Notice the OnClientClick event there is a js function called CheckReason, this function simply checks a textbox called reason to see if anyone has entered anything. If they haven't I do NOT want the ModalPopupExtender to actually open.
Here is that JavaScript function although ugly :)
function CheckReason()
{
var txtReason = document.getElementById('txtReason');
var txtReasonVal = txtReason.value;
if (txtReasonVal.length > 0 && txtReasonVal != 'Enter the reason for creating this expense report...')
{
return true;
}
else
{
txtReason.style.borderStyle='solid';
txtReason.style.borderColor='red';
return false;
}
}
The issue is even if I hit the else and return false, the modal popup extender still opens the modal popup. I need it so that it does not open up the pop up.
See if this helps
OnClientClick="javascript:var ret = CheckReason(); NoPrompt(); return ret;"

How to disable and Enable TextBox acording to checklbox

<asp:CheckBox ID="htmlChkNotify" runat="server" OnCheckedChanged="ToggleTextBox(this,'htmlTxtNotifyemailaddress')" />
<asp:TextBox ID="htmlTxtNotifyemailaddress" runat="server" Enabled="false"></asp:TextBox>
function ToggleTextBox(CheckBox, TextBoxID) {
var TextBox = document.getElementById(TextBoxID);
if (CheckBox.checked) {
TextBox.disabled = false;
TextBox.value = "";
}
else {
TextBox.disabled = true;
TextBox.value = "";
}
}
I have write like but when I run the code then error message comeing " can't be pass this literal" something like that, so how can I do it?
Actually u can also see demo in stackoverflow "Notify daily of any new answers" I want to fire event like.
Thank you
OnCheckChanged is expecting an ASP.Net event handler, it's not for JavaScript, for that attach your event handler like this:
htmlChkNotify.Attributes.Add("onclick",
"ToggleTextBox(this,'" + htmlTxtNotifyemailaddress.ClientID + "');");
I broke it down to 2 lines for readability here only, but the idea is to generate an onclick inline handler, rather than the server-side event handler it's currently trying to bind, in a place it can't pass this (which is why the parser fails).

Disallowing POST BACK when one is already in progress

Disable a post back from asp.net i.e. buttons, links, gridview page index changing and sorting etc when a post back is already in progress. Target browser is IE 6+. I've written these 2 javascript I am not sure how to apply it on GridView Page Index changing.
<script type="text/javascript">
//isFormSubmitted variable is used to prevent the form submission while the server execution is in progress
var isFormSubmitted = false;
//If the form is already submitted, this function will return false preventing the form submission again.
function SubmitForm(msg)
{
try {
if(isFormSubmitted == true)
{
alert('A post back is already in progress. Please wait');
return false;
}
else
{
var res = false;
if (msg)
{
res = confirm(msg);
}
if (res == true)
{
isFormSubmitted = true;
}
return res;
}
} catch(ex) {}
}
function VerifySubmit()
{
if(isFormSubmitted == true)
{
alert('A post back is already in progress. Please wait');
return false;
}
else
{
isFormSubmitted = true;
return true;
}
}
</script>
For buttons I can attach the SubmitForm to OnClientClick like this.
<asp:Button ID="btnCancel" runat="server" CssClass="button" Text="Cancel" OnClick="btnCancel_Click" OnClientClick="return SubmitForm('Do you want to continue with cancelling recent action?');" />
But I am not sure how to attach the VerifySubmit to non prompting controls like gridview pager.
onclick="this.disabled=true;"
on your submit-button(s) is all the javascript "magic" you need
When jQuery is an option you can use this small script to disable all submit-buttons:
// Find ALL <form> tags on your page
$('form').submit(function(){
// On submit disable its submit button
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Found here: http://jquery-howto.blogspot.com/2009/05/disable-submit-button-on-form-submit.html
Or you can block the whole page: http://jquery.malsup.com/block/#page
If you want to disable post back set autopastback=false for buttons links.
Otherwise you need to give us more information and better instructions / details to help you out.
I'm going to guess that you're doing ajaxy type stuff here and you have an async-postback going and you don't want the user to click a button at that time.
If that is the case then try the following code:
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
function startRequest(sender, e) {
//disable search button during the AJAX call
document.getElementById('<%=btnSearch.ClientID%>').disabled = true;
}
function endRequest(sender, e) {
//re-enable the search button once the AJAX call has completed
document.getElementById('<%=btnSearch.ClientID%>').disabled = false;
}
The easiest solution I found is that..
//In the head section define this script...
<script type="text/javascript">
function ShowProcessingMsg(confirmMsg) {
var resp = confrim(confirmMsg);
try {
if (resp == true) {
var divC = document.getElementById('<%= divControls.ClientID %>');
var divM = document.getElementById('<%= divProcessingMsg.ClientID %>');
if (divC && divM) {
divC.display = "none";
divM.display = "block";
}
else {
return false;
}
}
} catch (exp) { alert(exp); return false; }
return resp;
}
</script>
//This div will show during processing since by default it's display is none when after
//Post back your page loaded again this will not be diplayed. We are going to set it's
//diplay attribute to block from javascript.
<div id="divProcessingMsg" runat="server" display="none" z-index="1000" />
<b>Processing.... Please wait.</b>
</div>
//We will hide this div from script by setting its display attribute to none. Since
//by default this attribute is block when the page loaded again it'll be displayed by
//default. So no special handling for setting display again to block is required.
<div id="divControls" runat="server" display="block" z-index="1" />
<asp:GridView ............ >
.....
.....
.....
<asp:Button runat="server" id="btnProcess" Text="Process" OnClientClick="return ShowProcessingMsg('Do you want to continue with processing'); OnClick="btnProcess_ServerClick" />
</div>

Categories