Button event not stopping - asp.net

I am using DOJO (1.7) together with ASP.NET. I have attached an onclick event to the submit button but am trying to validate on client side first. In plain javascript, if I used a 'return false' statement, that stopped the postback. However, returning false in the code does not stop the statement while using DOJO. I am a DOJO newbie and have no idea what to do. Thank you for your time.
require(["dojo/io/script", "dojo/on", "dojo/dom", "dojo/domReady!"],
function (script, on, dom) {
on(dom.byId("<%= btnSubmit.ClientID %>"), "click", function () {
dom.byId("<%= txtSellPercentage.ClientID %>").value = "farax";
return false;
}
)
});

I had to tweak the code a little. Apparently I was trying to call some event method without importing the particular script for events. So here goes
<script type="text/javascript">
require(["dojo/io/script", "dojo/on", "dojo/dom", "dojo/domReady!", "dojo/_base/event"],
function (script, on, dom, event) {
on(dom.byId("<%= btnSubmit.ClientID %>"), "click", function (e) {
dom.byId("<%= txtSellPercentage.ClientID %>").value = "farax";
event.stop(e);
}
)
});
</script>

Related

Why does my jquery-ui modal dialog disappear immediately after it opens?

I'm trying to use a simple jquery-ui modal dialog as a delete confirmation in an ASP.NET C# application. I've done this many times before, but for some reason in this application it is misbehaving. I see the dialog pop up then it immediately disappears before I can click on either "Yes" or "No". Here's the relevant code (Javascript):
<script type="text/javascript" src="/resources/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.9.1.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.9.1.custom.css" />
<script type="text/javascript">
var remConfirmed = false;
function ConfirmRemoveDialog(obj, title, dialogText) {
if (!remConfirmed) {
//add the dialog div to the page
$('body').append(String.Format("<div id='confirmRemoveDialog' title='{0}'><p>{1}</p></div>", title, dialogText));
//create the dialog
$('#confirmRemoveDialog').dialog({
modal: true,
resizable: false,
draggable: false,
close: function(event, ui) {
$('body').find('#confirmRemoveDialog').remove();
},
buttons:
{
'Yes, remove it': function() {
$(this).dialog('close');
remConfirmed = true;
if (obj) obj.click();
},
'No, keep it': function() {
$(this).dialog('close');
}
}
});
}
return remConfirmed;
}
//String.Format function (since Javascript doesn't have one built-in
String.Format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
</script>
Here's where I'm using the confirmation function (in the OnClientClick of an <asp:Button> control):
<asp:Button ID="btnRemoveProgram" runat="server" Text="Remove" CausesValidation="false" OnClientClick="ConfirmRemoveDialog(this, 'Please confirm removal', 'Are you sure you wish to remove the selected Program? This cannot be undone.');" />
As I said, I've successfully used this same construct (nearly identical code) many times before; I don't know why it isn't working now. Any ideas will be greatly appreciated, I'm truly stumped on this one.
The runat="server" is telling the button that it should post back to perform events at the server. The OnClientClick will be executed before that on the client side, so you will see the dialog and then immediate the page posts, causing the dialog to disappear.
The problem is that your modal dialog box is not modal in the traditional windows sense. The javascript continues on. The simplest test is to add an alert right before your return, you will see it pops up right after the dialog is shown.
To get around this issue, return false always in the OnContentClick and then in your Yes/No button event handlers use the __doPostback javascript method.
You need to return the remConfirmed to the caller which is the button itself. On your button, do this:
OnClientClick="return ConfirmRemoveDialog(/* the rest of the code */);"

Why jquery .live() and .on() don't work as expected for ASP.NET Updatepanels?

I have 1 page which has 1 updatepanel which contains 1 user control(lets call it user.ascx) and 2 buttons.
My user.ascx has some checkboxes which can disable/enable other controls. I am doing it in javascript added to user.ascx, but when updatepanel updates( async postback after clicking 1 of those 2 buttons) my javascript events for checkboxes (click or change) arem't fired.
I know I can just wrapp $().ready() with function pageLoad(sender,args) and it works perfect but according to that page http://blog.dreamlabsolutions.com/post/2009/03/25/jQuery-live-and-ASPNET-Ajax-asynchronous-postback.aspx it is better to use live() function.
Unfortunately all available ways to bind event like .click(), .change(), .bind(), .live() and .on() work after postback can't after asynchronus postback.
Sample of code which doesn't work:
<script type="text/javascript">
$().ready(function () {
var ddlAge= $("#<%= ddlAge.ClientID %>");
var cboxFirst= $("#<%= cboxFirst.ClientID %>");
var cboxSecond= $("#<%= cboxSecond.ClientID %>");
$(document).on("change", cboxFirst, function () {
if (cboxFirst.is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
cboxSecond.live('change',function () {
if (cboxSecond.is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
});
</script>
Both checkboxes work only after postbacks. What may I do wrong? Does anyhone have such problem? I am using Jquery 1.7.1 and I am not getting any js errors.
I will be grateful for any help.
I'm surprised that the .on works at all. According to the documentation http://api.jquery.com/on/ it's second parameter should be a selector string and not a jquery object.
I would try something like this:
$(document).on("change", "#<%= cboxFirst.ClientID %>", function () {
if ($(this).is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
As long as the ClientID stays the same the event will still work even when the UpdatePanel replaces all its content.
Also, .live has been deprecated in favor or .on

sender._postBackSettings.sourceElement is undefined

This is what I'm trying to do -
Using jQuery when the document is ready and if the page is not postback I issue a manual postback for an updatepanel to retrieve data from a database.
While the updatepanel is getting the data I present an updateprogress which I hide when the specific updatepanel finishes. I also want to "BLOCK" the screen from any interaction. After the data is loaded I have additional buttons on the form and I want to block everything in case of any partial-postback.
Here is the code:
$(document).ready(function ()
{
if(<% =(Not Page.isPostBack).ToString().ToLower() %>)
{
__doPostBack('upShipping');
}
}
function pageLoad() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args)
{
$('.blur').css("display", "block");
if (args._postBackElement.id == 'upShipping') {
$get('divCalculating').className = 'Show';
}
}
function EndRequestHandler(sender, args)
{
$('.blur').css("display", "none");
if (sender._postBackSettings.sourceElement.id == 'upShipping')
{
$get('divCalculating').className = 'Hidden';
}
}
If I do not "CLICK" on the screen everything works great. But if I just click anywhere on the screen while the updatepanel updates the "EndRequestHandler" doesn't fire and I'm stuck with the loading gif and blocked screen.
I get the following error in the error console of the browser: sender._postBackSettings.sourceElement is undefined
Any ideas?
Thanks!
Nick
For some reason sender._postBackSettings.sourceElement kept coming back as NULL in the EndRequestHandler.
I defined a global var, assigned it a value at the BeginRequestHandler and checked its value instead in the EndRequestHandler.
This solved the problem.

Jquery help needed for onbeforeunload event

I am using jquery onbeforeunload event in asp.net application.
If i write event as given below then its working fine and display confirm dialog box.
var vGlobal = true;
var sMessage = "Leaving the page will lost in unsaved data!";
[ Working ]
> window.onbeforeunload = function() {
> if (vGlobal == false) return
> sMessage; }
but its not working if i use bind method like as given below
[ Not working ]
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
Anybody suggest me why its not working.Is there any difference between these two methods.
Code on aspx:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
CLICK ON THIS LINK TO SEE RUNNING EXAMPLE
See the updated version
You need to bind all the events inside document ready event.
Apart from the fact that vGlobal is true and you are checking if (vGlobal == false), this smells like a $(document).ready() issue.
I.e. you should place the declaration inside a document.ready() handler as shown here:
$(document).ready(function(){
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
});
There is no benefit in using jQuery to bind the event to the window - all you are doing is adding the overhead of having jQuery parse the window into a jQuery object, which you aren't even using.
Therefore, using:
window.onbeforeunload = handler;
Is preferable to using jQuery to bind this event.
You can still perform the binding inside of the document ready section:
$(document).ready(function () {
window.onbeforeunload = handler;
};

asp.net external JavaScript file doesn't find Control.ClientID

On load I'm both calling a JavaScript setTimeout() function that will hide a .NET Panel control, and hiding it in the code behind on first load. Clicking the save button will set the Panel to visible then reload the page at which point a setTimeout() function is called... so basically you click save, and see a panel with "Details Saved" for three seconds, at which point it disappears.
The problem is the external JavaScript file can't find _pDivAlert.ClientID (I've debugged and it returns null). It only works when the code is in a tag in the .aspx page. Any suggestions as to how I can either pass the client ID to the HideControl() function or find the ClientID from the external JS file?
Here's my code, any suggestions?
<script language="javascript" src="Forms.js" type="text/javascript"></script>
<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
//alert the user that the details were saved
function HideControl() {
var control = document.getElementById('<%=_pDivAlert.ClientID %>');
if(control != null)
control.style.display = 'none';
}
function ToggleAlert() {
setTimeout("HideControl()", 3000);
}
</script>
I've also tried sending the ClientID within the ToggleAlert() call, but that didn't work:
<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">
External JS:
function HideControl(_c) {
var control = _c;
if (control != null)
control.style.display = 'none';
}
function ToggleAlert(_c) {
setTimeout("HideControl(_c)", 3000);
}
can you show your markup with the panel and the codebehind where you hide it?
there's a difference between setting the Visible property to false and setting the style display attribute to none- the first will not render the element at all, meaning there isn't anything rendered with the id you're looking for.
edit: it's probably because of the way you're calling HideControl in the timeout- this should be a function instead of a string.
try doing
function ToggleAlert(_c) {
setTimeout(
function () {
HideControl(_c);
}, 3000);
}
just for clarity, when you pass a string to setTimeout, it's evaluated and then run. the code chunk that eval produces will run in a different scope than your ToggleAlert method, and so _c won't be available at that time.
edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.
function HideControl(_c) { // _c is the id of the element
var control = document.getElementById(_c);
if (control != null)
control.style.display = 'none';
}

Resources