How to Prevent Javascript Function Firing When ASP.NET Validation is Used - javascript

I'm calling a JavaScript DOM button click event to execute some code. However, I first need to validate if a textbox has a value in it. So, I'm using ASP.NET's RequiredFieldValidator control to validate the textbox. It works in that it will display an error message when the textbox is empty, however, the associated JavaScript button click event still fires.
How to do I prevent the JavaScript function from firing when I use an ASP.NET validation control?
By the way, I know I can use validation within JavaScript, but I'm hoping not to do that and just use ASP.NET validation controls only.
Here is my code (it's exactly how used with all the fluff removed):
<%# Page Language="VB" blah... %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="MyButton" runat="server" Text="Click Me" />
<asp:TextBox runat="server" ID="MyTextBox"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="MyRequiredFieldValidator" ControlToValidate="MyTextBox" Display="Dynamic" Text="*" ErrorMessage="The field is required.">
Required
</asp:RequiredFieldValidator>
</form>
<script type="text/javascript">
$(document).ready(function () {
const vMYBUTTON = document.querySelector('#MyButton');
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function () {
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
});
</script>
</body>
</html>

The issue is that the form submit is a click event, which is separate from the button click event.
Both of those events enter the queue one right after the other.
When the form is submitted, the server returns the required field error, then the next click event is processed which happens to be the JavaScript that you don't want to be called.
The server will need to render a page without the script until there are no errors
<!DOCTYPE html>
<html lang="en">
<head runat="server"></head>
<body>
<!-- /////////////////////////////////////////////////////////////
// Both the button click, and the JavaScript click events are
// triggerd when the form returns an error
///////////////////////////////////////////////////////////////-->
<form id="form1" runat="server">
<!-- /////////////////////////////////////////////////////////////
// When this button is clicked, it fires its own click event
///////////////////////////////////////////////////////////////-->
<asp:Button ID="MyButton" runat="server" Text="Click Me" />
<asp:TextBox runat="server" ID="MyTextBox"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="MyRequiredFieldValidator" ControlToValidate="MyTextBox" Display="Dynamic" Text="*" ErrorMessage="The field is required.">
Required
</asp:RequiredFieldValidator>
</form>
<script type="text/javascript">
$(document).ready(function() {
const vMYBUTTON = document.querySelector('#MyButton');
/////////////////////////////////////////////////////////////
// This event will fire because it is an
// additional click event that you are adding
/////////////////////////////////////////////////////////////
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function() {
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
});
</script>
</body>
</html>
You could do something simple to control the behavior by adding a variable to track the status of the form.
///////////////////////////////////////////////////////////////
// This event will be ignored until the server returns success
///////////////////////////////////////////////////////////////
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function() {
if (someVariableSetOnTheServer == "invalid form") {
return;
}
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
Another method would be to use the .NET JavaScript API to only run the code when Page_ClientValidate() returns true
if (Page_ClientValidate()) {
// run your code here
}

Related

DropDownList loses its property after using updatePanel in asp.net

I have below code to have intelligent dropdownlist in asp.net to have the search property there
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); </script>
The problem is that whenever I use updatepanel in this way:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<fieldset>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
after that: it loses its property and returned as normal dropdownlist. Any idea how to fix this and make the update panel do not recreate the dropdownlist to its previous property?!
You need to execute that script again after an UpdatePanel update. Since the DOM still changes and the browsers loses the script bindings. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
//for after an updatepanel update
prm.add_endRequest(function () {
buildDropDownList();
});
//for normal page load
buildDropDownList();
function buildDropDownList() {
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({ allow_single_deselect: true });
}
</script>

Cannot call blockUI function from asp button

First of all it does work as a regular button:
<input type="button" value="Block" id="btnBlock" name="btnBlock"/>
But I need to work on an asp:button as well, I've tried this:
<asp:Button ID="btnBlock" runat="server" Text="Block" OnClientClick="btnClick"/>
But it doesn't work, just sends a JS error (edited):
Microsoft JScript runtime error: 'btnBlock' is undefined
My JS blockUI function:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#btnBlock').click(function() {
$.blockUI({ message: $('#myForm') });
});
});
</script>
I've also tried changing the blockUI function to this, but it doesn't seem to work, it doesn't recognize the asp code inside the script:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#<%= btnBlock.ClientID %>').click(function() {
$.blockUI({ message: $('#myForm') });
});
});
</script>
In your asp button markup you've got
OnClientClick="btnClick"
This sets the client-side script that executes when a Button control's Click event is raised. That is the fired event looks for a javascript function called btnClick. The issue is that you are wiring the click event via jQuery $(selector).click(someFunction); and also in the OnClientClick event.
Change the asp button control to remove the OnClientClick event:
<asp:Button ID="btnBlock" runat="server" Text="Block" />
Keeping the javascript the same.

How to check If "mywindow" tab of the browser is active or not in asp.net 4.0?

Actually i am making website of online test/exam in asp.net using c# 4.0. And for giving exam the user needs to click on a button which will open a window with a JavaScript function.
function OpenForm() {
window.open('Test.aspx', 'mywindow',
'fullscreen=yes,titlebar=no,toolbar=no,statusbar=no,menubar=no');
}
And the thing i want is, while a Exam is going on, if user changes its tab or open a folder in his/her pc then i want to close the window i.e. "mywindow". i know its not possible in asp.net to achieve this so want to know how can i achieve this in javascript or jquery?
i have search out the net for few answers and now i know how to call a JavaScript function every time my "test.aspx" or "mywindow" page loads.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args)
{
yourFunction();
}
function yourFunction()
{
alert("aaa");
}
function pageLoad()
{
if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
</script>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="6000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</form>
//i need to right the logic in yourFunction() to check whether "mywindow" or "test.aspx" is active or not if yes then i will display a message on alert("u are disqualified") and then close the "test.aspx"
Please someone help me out with this!!! please...!!
This is how I did it... I tested in Chrome/Opera/Firefox/IE... In IE it asked for permission to close the window on all the others it closed automatically....Not sure how to get around the IE bug at the moment.
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).focus();
$(window).blur(function () {
window.opener.BadStudent();
window.close();
});
$('#close').click(function () {
window.close();
});
});
</script>
EDIT: This script is placed on the page that they would end up on. Also I added a form element just to ensure that the window wouldn't close when a child element was selected and I didn't have any issues.
EDIT 2: The IE bug was due to javascript not opening the window. so insted use...
Link
and then...
<script type="text/javascript">
function BadStudent () {
alert("Your a bad student");
};
$(document).ready(function(){
$('#OpenWindow').click(function(e){
e.preventDefault();
Popup = window.open("#Url.Action("test")").focus();
});
});
</script>
The script that goes on the child window is still valid. Also this was done using jQuery for the selectors.

How to tell if a page unload in ASP is a PostBack

This seems like a common question but search is not returning anything.
I have the following code that executes before the page unloads.The problem is if the unload is a postback i do not want to fire my warning to the user but i can't figure out how to differentiate between a postback and a user navigating to another page for example.
// This is executed before the page actually unloads
$(window).bind("beforeunload", function () {
if (prompt) {
//prompt
return true;
}
else {
//reset our prompt variable
prompt = true;
}
})
Running script in the code behind i.e. if Page.IsPostBack then set prompt is not an option.
Any ideas?
EDIT:
Here is the solution I ended up with:
function DoNotPrompt() {
prompt = false;
}
I then added this to all the controls where the user could do something that result in a post back.
OnClientClick="DoNotPrompt()
Then checked this flag and only returned a string in "beforeunload" if the user was really moving away from the page i.e. not a postback.
I also had to use this code:
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
prompt = false;
}
The reason being i had a custom user control that was a list box and I could not add the above method. So used this to catch that event and set the flag to false.
Not the most elegent solution.
Thanks,
Michael
You can capture the submit and reset the onbeforeunload as:
jQuery(function($) {
var form = $('form'), oldSubmit = form[0].onsubmit;
form[0].onsubmit = null;
$('form').submit(function() {
// reset the onbeforeunload
window.onbeforeunload = null;
// run what actually was on
if(oldSubmit)
oldSubmit.call(this);
});
});
This is a tested code from my pages :)
This may not cover all of the postback situations, but you can tell if the page was posted back by an ASP control by interrogating the __EVENTTARGET hidden input.
This input is set by ASP when the page is posted back by an ASP control.
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
}
JavaScript runs on the client; as far as the client is concerned, a page does not maintain state from one view to the next. Postbacks are entirely an ASP.NET concept.
You can get around this by running some code on the server-side which defines a JavaScript variable based on whether or not Page.IsPostBack is true.
Example:
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page.IsPostBack -> client</title>
<script type="text/javascript">
var isPostback = <%= Page.IsPostBack %>;
console.log("IsPostBack: " + isPostback);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnTest" Text="Click me..." />
</div>
</form>
</body>
</html>

jQuery function before the Postback for FileUpload in ASP.NET

So, I have an .aspx webpage as follows:
..
<form id="frm" runat="server">
<asp:FileUpload runat="server" id="fileupload" onchange="browsed()" />
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton" class="uploadbutton" Text="start upload" Enabled="false" />
<div id="nfo" style="display: none">
blabla
</div>
</form>
..
Now, as you can guess correctly, user chooses file to upload, clicks #uploadbutton and, voila, Upload_Click is called after the postback.
Then, I want to show div #nfo with some jQuery effects during the upload. To do this, I write:
$(function() {
$('.uploadbutton').click(function() {
$('#nfo').slideDown().show("fast");
})
})
and everything works just fine, until the user starts browsing in IE...
First of all, in IE, user has to click #uploadbutton twice - first time to display #nfo, second time, for some reason, to initiate postback.
Secondly, after the postback, Upload_Click's this.fileupload.HasFile shows false.
FF and Chrome works quite well though.
As far, as I can understand this - in IE jQuery's function prevents something important for asp:FileUpload from happening and stops the postback. Though, on the second click it does initiate the postback, but still with no info for asp:FileUpload's Upload_Click.
Any help?
Update:
followed #joelt'd advice. turned out, there was some different problem, never thought it could be of importance, so I didn't provide source code for that part =(
see localizing <asp:FileUpload>. IE problem
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
$("#progress").show();
});
});
</script>
</head>
<body>
<form runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<div id="progress" style="display:none; background-color:Red;">test</div>
</form>
</body>
</html>
This works fine for me in FF and IE7, except in IE, the progress indicator doesn't really give you anything because of how it's rendering, I suppose. I would say the biggest difference between our code is the "onchange=browsed()" function. It's possible that's not getting called until you click the button? In any case, I would start with a stripped down page like this, and start adding in other elements you have until it breaks.
try this:
<asp:Button runat="server" OnClick="Upload_Click" id="uploadbutton"
class="uploadbutton" Text="start upload" Enabled="false"
OnClientClick="return myFunction();"/>
<script type="text/javascript">
function myFunction(){
$('#nfo').slideDown().show("fast");
return true;//THIS WILL FIRE POSTBACK EVENT
//return false;//THIS WILL STOP POSTBACK EVENT, WHICH YOU MAY WANT IF THERE
//IS NO FILE SELECTED
}
</script>

Categories

Resources