Prevent JavaScript OnClick binded confirm() to override VB.NET Click handler - javascript

I have to resolve a problem in some code assigned to me and the problem is that following this code in page.init else statemant:
Me.SaveChangesButton.Attributes.Add("OnClick",
"if (!confirm('Are you sure?')){
return false;
} else {
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}
")
overrides this code:
Protected Sub SaveChangesButton_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles SaveChangesButton.Click
Question [edited]
How can I bind confirm() to button so that it doesn't override my handler function?
Where in the code would it be best practice to bind it?
If I remove second part else {document.getElementById('SaveChangesButton').disabled =
true; document.getElementById('rejectButton').disabled = true;} it works correctly, but how should I write it so it continues to execute SaveChangesButton_Click, as I understand only the second part overrides handler?
How can I execute those two lines document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true; and still execute SaveChangesButton_Click handler without overriding it?

1) You should use OnClientClick:
Me.SaveChangesButton.OnClientClick = #"
if (!confirm('Are you sure?')) {
return false;
} else {
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}"
2) If you bind the SaveChangesButton_Click in the Page.Init, I would then set the OnClientClick too.
3,4) The OnClientClick fires (sort of) before the server side OnClick (of course). This makes you disabling your button, before firing the OnClick. And OnClick won't fire on a disabled button. What to do? Delay disabling your button.
Me.SaveChangesButton.OnClientClick = #"
if (!confirm('Are you sure?')) {
return false;
} else {
setTimeout(function(){
document.getElementById('SaveChangesButton').disabled = true;
document.getElementById('rejectButton').disabled = true;
}, 100);
}"
And this actually makes your question a duplicate of this one...

Related

How to return a value from a jQuery event function to the parent function?

I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}

On Click When Button is Disabling then Click Button is not firing

When I am Clicking on button of asp.net then on client click I am disabling that clicked button then server side click event is not firing.
My code is as following:
<asp:Button ID="ButtonSend2" runat="server" CssClass="CommonButtonStyle" Text="Send Message" OnClientClick="this.disabled='true';return OnClickSendEmail();"
OnClick="btnSend_Click" ValidationGroup="ValidationGroupCompose" />
and This is my Java script code:
function OnClickSendEmail() {
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
return false;
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
console.log("Value is returing true");
return true;
}
}
Once the button is disabled, the postback is not made. You could re-enable the button at the end of the processing but there is another problem: the display will not be updated when the browser is busy processing OnClickSendEmail(), so the button will never look disabled.
Here is a possible solution, which involves canceling the postback at first and processing the command asynchronously:
<asp:Button ID="ButtonSend2" runat="server" OnClientClick="this.disabled = true; setTimeout(OnClickSendEmail, 0); return false;" ... />
The postback is then triggered with __doPostBack at the end of the lengthy processing:
function OnClickSendEmail() {
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
console.log("Value is returing true");
__doPostBack('<%= ButtonSend2.UniqueID %>', '');
}
}
On your javascript code, there are two points that can cause not firing at the end. I write on the code the possible points. Also you have include it on ValidationGroupCompose validation, are you sure that is not stopped from there ?
function OnClickSendEmail() {
// !!! if the element not found is throw an error here and not continue at all.
var value = document.getElementById('CE_ctl00_ContentMain_TextArea_ID').getHTML().replace(/ /g, "").trim();
if (value == "" || value == undefined) {
$j('#ctl00_ContentMain_lblMessage').text('Message body can\'t be blank!');
$j('#ctl00_ContentMain_lblMessage').show()
// !!!! if comes here and return false, then is NOT firing, not continue.
return false;
} else {
$j('#ctl00_ContentMain_lblMessage').text('');
// !!!! if comes here and you not use a browser that support the console, function, is thrown an error and not continue to fire up.
console.log("Value is returing true");
return true;
}
}
Debug your javascript to see whats going wrong, also remove the console.log from your final code.

Can't make sens out of javascript event and functions

Here is the code that works as-is, a classic onBeforeUnLoad event, in the <script type="text/jscript"> tag of my ASP page :
window.onbeforeunload = function (e) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "do you wish to save?";
}
Now, two issues i'm experiencing when wanting to do something more complex :
I want this to appear only once at all cost :
var a = 0;
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "Wish to save?";
}
}
//Does not work...
I want it to be able to run this other function that works when not combined with the first :
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
// works, but not when combine to the first function
I tried to put this all together... I want the unload event to make my confirm box function run :
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
}
And now I realize I'm far from being an expert of javascript...
The beforeunload event won't run any obtrusive Javascript for the user (ie alert, confirm etc).
But there is an workaround, the steps should be something like:
Create a boolean flag to check if the user has canceled the exiting of your page (default false).
Create the beforeunload event handler, and check if the game is not
saved.
If it was already saved, then, you do nothing, and let the user go
But if it was not, then you change that boolean flag to true.
You keep an interval dirty-checking if that variable is true, and at anytime it is, you save the game for the user, and then set this variable to false again.
So, doing that, you'll ensure the user always see a message if they're leaving without saving, and if they cancel the exiting, the game will be automatically saved, making the next try pretty smooth.
Take a look at the example below. To test it, open your console, click on Run. Then, try to click on Run again, and you'll see an exiting message. If you confirm it, your console won't show anything. But if you cancel it, then, you'll be kept in the page, then you try to click Run again, and you'll see that no message will appear, but the console will log true.
(function() {
var game = { saved: false };
var canceled = false;
setInterval(function() {
if (canceled) {
game.saved = true;
canceled = false;
}
}, 100);
window.onbeforeunload = function() {
if (!game.saved) {
canceled = true;
return 'Are you sure?';
}
else {
console.log(game.saved);
}
}
})();

Check validation and disable button on click

I have an ASP.NET application and I have implemented the below code to disable users from double clicking and a submit button and thus the method behind the code is not executed than once.
OnClientClick="this.disabled = true; this.value = 'Submitting...';" UseSubmitBehavior="false" onclick="BtnSubmit_Click"
This was working perfectly, but on one of the pages I had implemented javascript forms validations and the below code is not working:
OnClientClick="return validation(); this.disabled = true;" UseSubmitBehavior="false" onclick="BtnAdd_Click"
The validation is to make sure user does not leave any empty fields, however on clicking the button if validation is success, the button is disabled but the onclick method is not being called.
Why exactly is this happening?
Rikket, you'll have to write separate code to prevent double submission of forms, once its submitted, a Jquery function will help probably, something like below, put this after your JavaScript validation function:
jQuery.fn.preventDoubleSubmission = function () {
var $form = $(this);
$form.on('submit', function (e) {
if ($form.data('submitted') === true) {
e.preventDefault();
} else {
$form.data('submitted', true);
}
}).find('input').on('change', function () {
$form.data('submitted', false);
});
return this;
};
And can be called after your validation inside the else :
if (nullFieldTracked == 'true') {
alert(nullExceptionMsg);
return false;
}
else {
$('form').preventDoubleSubmission();
}

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories