Strange behavior of confirmation in Telrik ? - javascript

somePage.aspx
<asp:LinkButton Runat="server" ID="butDelete" CommandName="Delete" OnClientClick="Confirmation();return flag;"><img src="images/delete.gif" border="0" title='<asp:Literal runat="server" Text="<%$ Resources:ClarityResources, resDelete %>" />'></asp:LinkButton>
ClientSideCode.js
function confirmCallBackFn(sender) {
debugger;
if (sender)
flag = true;
else
flag = false;
return flag;
}
function Confirmation(sender,args) {
debugger;
radconfirm('Are you sure you want to delete this file?', confirmCallBackFn);
}
but the on click always returns false which is default value set for the flag variable
When i did debugging i seen that the on client click the method confirmation gets called and it returns the default value false to the control and after clicking on the confirmation box's Yes or cancel it again runs the call back method confirmCallBackFn(sender) seperatly which returns flag but not in same thread but in different thread. I tried different ways to solve it but i am stuck . so any help would be great .

You're trying to treat the radconfirm in the same way as a plain javascript confirm(), this isn't done in a like-for-like manner. I'll start with the Confirmation function.
function Confirmation(sender, args) {
debugger;
// The line below will open a rad confirmation window, it will not wait for the response
radconfirm('Are you sure you want to delete this file?', confirmCallBackFn);
}
To ensure that it doesn't automatically post back the above function should be changed as follows:
function Confirmation(sender, args) {
debugger;
// This line will open a rad confirmation window, it will not wait for the response
radconfirm('Are you sure you want to delete this file?', confirmCallBackFn);
// The line below will prevent the control from automatically posting back
return false;
}
The next step is correcting the call back function; The parameter passed into the function, as can be seen from the code rather than the parameter name is the boolean representation of the result from the confirmation box.
function confirmCallBackFn(sender) {
debugger;
if (sender)
flag = true;
else
flag = false;
return flag;
}
The previously written function returns a value, but this isn't used anywhere. The following code will perform the required action
function confirmCallBackFn(arg) {
debugger;
if (arg) {
// The line below will perform a post back, you might want to trigger this a different way
__doPostBack(sender.id, "");
}
}
Unfortunately as the sender is not passed into the callback function it is necessary to declare the function within the other JavaScript function as follows:
function Confirmation(sender) {
debugger;
// The callback function
function confirmCallBackFn(arg) {
debugger;
if (arg) {
// Triggers postback only when confirmation box returns true
__doPostBack(sender.id, "");
}
}
// This line will open a rad confirmation window, it will not wait for the response
radconfirm('Are you sure you want to delete this file?', confirmCallBackFn);
return false;
}
You might find the following link useful in regards to using the radconfirm in the same way as a confirm:
http://demos.telerik.com/aspnet-ajax/window/examples/confirmserverclicks/defaultcs.aspx.

This is how I alert user to confirm the delete event !
<telerik:RadButton ID="btnDelete" runat="server" Text="Delete"
OnClick="btnDelete_clicked" OnClientClicking="RadConfirm" Width="100px">
</telerik:RadButton>
<script type="text/javascript">
function RadConfirm(sender, args) {
var callBackFunction = Function.createDelegate(sender, function (shouldSubmit) {
if (shouldSubmit) {
this.click();
}
});
var text = "Are you sure you want delete ?";
radconfirm(text, callBackFunction, 300, 100, null, "Confirm Apply !");
args.set_cancel(true);
}
</script>
protected void btnDelete_clicked(object sender, EventArgs e)
{
//Write your server-side delete code here
}

Related

beforeinstallprompt triggers on every load

Beforeinstallprompt triggers on every load.
I have used the code here: https://developers.google.com/web/fundamentals/app-install-banners/
I am not using the The mini-info bar which i have dissabled by calling e.preventDefault();
The problem is that the showAddToHomeScreen(); is called on every load if the user does not click addToHomeScreen.
I want the showAddToHomeScreen(); function to be called only every month or so by storing information about the last "canceled" click in sessions or something similar. Isn't google suppose to do this on it's own?
This i found on the following link:
https://developers.google.com/web/updates/2018/06/a2hs-updates
You can only call prompt() on the deferred event once, if the user clicks cancel on the dialog, you'll need to wait until the beforeinstallprompt event is fired on the next page navigation. Unlike traditional permission requests, clicking cancel will not block future calls to prompt() because it call must be called within a user gesture.
window.addEventListener('beforeinstallprompt', function (e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
showAddToHomeScreen();
});
function showAddToHomeScreen() {
var prompt = document.querySelector(".a2hs-prompt");
prompt.style.display = "flex";
var open = document.querySelector(".a2hsBtn");
open.addEventListener("click", addToHomeScreen);
var close = document.querySelector(".a2hsBtn-close");
close.addEventListener("click", function() {
prompt.style.display = "none";
});
}
function addToHomeScreen() {
var prompt = document.querySelector(".a2hs-prompt");
// hide our user interface that shows our A2HS button
prompt.style.display = 'none';
if (deferredPrompt) {
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then(
function (choiceResult) {
if (choiceResult.outcome === 'accepted') {
show_ad2hs_success_message();
}
deferredPrompt = null;
});
}
}
You have to define your own session and add expire date. This is simple with ajax. This is how i did:
Javascript:
$(document).ready(function() {
$.ajax({
url: '/update_session_addtohomescreen',
success: function (session_expired) {
if(session_expired=='True'){
showAddToHomeScreen();
}
},
error: function () {
alert("it didn't work");
}
});
});
This is wrapping the showAddToHomeScreen(); function
View
#csrf_exempt
def update_session_addtohomescreen(request):
if request.is_ajax():
number_of_days_till_expire = 1
now_in_secs = time.time()
if not 'last_session_coockie' in request.session or now_in_secs > request.session['last_session_coockie']+60:#number_of_days_till_expire*86400:
session_expired = True
request.session['last_session_coockie'] = now_in_secs
else:
session_expired = False
return HttpResponse(session_expired)
return None
You should though include csrf token in your request and also add the url to urls.py

Use JavaScript to submit Ajax.BeginForm()

I'm typing this question away from my computer so I don't have the exact code, but the question might be straightforward enough without it.
When I have a submit button directly within an Ajax form and I click the button directly to submit, everything works fine, and as expected. The Ajax.Form POSTs back to the controller which returns a partial view that is rendered inside the current View that I have.
But what I need is for a button to be clicked in the Ajax.Form, and for a JavaScript function to run. The JavaScript function will do some vaildation which decides whether to submit the Ajax.Form or not.
I have tried putting 2 buttons in the Ajax.Form, a hidden submit button and a regular button. I used the onclick event of the regular button to call my JavaScript function which then called the click method of the hidden submit button. (I have also tried just submitting the Ajax.Form directly with document.forms[formname].submit() )
This sort of works.. But not correctly for some reason. The Ajax.Form POSTs back to the controller but when a partial view is returned from the controller, the partial view is the only thing rendered, and it is rendered as basic html with no css/bootstrap.
What is the difference between actually clicking the submit button and doing so programmatically?
How can Achieve what I am trying to do?
Edit
#using (Ajax.BeginForm("GetInstructorInfo", "Incident", FormMethod.Post, new AjaxOptions { OnBegin = "lookupInstructor();", UpdateTargetId = "InstructorInfo" }, new { #class = "form-inline", role = "form", #id = "instructorInfoForm", #name = "instructorInfoForm" }))
{
//code in here
}
Edit 2 / 3:
<script>
function lookupInstructor()
{
if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) //Don't allow user to enter multiple instances of the same Instructor
{
document.getElementById("InstructorUsername").value = ''; //clear textbox value
return false;
}
var userInputInstructor = document.getElementById("InstructorUsername").value;
$.ajax({
url: '#Url.Content("~/Incident/LookUpUsername")',
data: { userInput: userInputInstructor },
success: function (result) {
if (result.indexOf("not found") != -1){ //if not found
$("#InstructorNotFoundDisplay").show();
document.getElementById("InstructorUsername").value = ''; //clear textbox value
$('#InstructorInfo').empty();
return false;
}
else {
$("#InstructorNotFoundDisplay").hide();
return true;
}
}
});
}
</script>
You can use the OnBegin() ajax option to call a function that runs before the form is submitted (and return false if you want to cancel the submit). For example
function Validate() {
var isValid = // some logic
if (isValid) {
return true;
} else {
return false;
}
}
and then in the Ajax.BeginForm() options
OnBegin = "return Validate();"
Edit
Based on the edits to the question and the comments, you wanting to call an ajax function in the OnBegin() option which wont work because ajax is asynchronous. Instead, use jQuery.ajax() to submit you form rather than the Ajax.BeginForm() method (and save yourself the extra overhead of including jquery.unobtrusive-ajax.js).
Change Ajax.BeginForm() to Html.BeginForm() and inside the form tags replace the submit button with <button type="button" id="save">Save</button>and handle its .click() event
var form = $('#instructorInfoForm');
var url = '#Url.Action("GetInstructorInfo", "Incident")';
var target = $('#InstructorInfo');
$('#save').click(function() {
if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) {
....
return; // exit the function
}
$.ajax({
....
success: function (result) {
if (result.indexOf("not found") != -1) {
....
}
else {
$("#InstructorNotFoundDisplay").hide();
// submit the form and update the DOM
$.post(url, form.serialize(), function(data) {
target.html(data);
});
}
}
});
});

JavaScript - Multiple signals received after click

I'm creating a webapp using jQueryMobile. When I'm using the app and I click a button it runs the script multiple times.
For example:
I have a submit button:
<input type="submit" id="login-normal" value="Login" />
And I have this JavaScript for debugging on which this error occurs:
$("input#login-normal").live('click',function() {
console.log("Test");
});
On the very first click it works (and it goes to another screen for example), but when I go back to that screen and I click again, it outputs multiple console.logs
edit
this is the exact code as in my .js file.
$("div#login input#login-normal").live('click',function() {
var email = $("input#email").val();
var password = $("input#password").val();
user.checkUser(email, password, function(exists) {
if (exists) {
$.mobile.changePage("#home", { transition: "slidedown"});
} else {
console.log("Wrong email or password.");
}
});
console.log("Login");
});
user.checkUser is an object from my class User which checks if the user exists in the database (WebSQL). returns true of false on callback.
Can you use on instead of live and try it like
$("input#login-normal").off('click').on('click',function() {
//...
});
Try
$.mobile.activePage.find("div#login input#login-normal").live('click',function() {...}
If that still fires multiple times you can try
$(document).delegate("[data-role=page]", "pagebeforeshow", function () {
$("div#login input#login-normal").bind("click", function (e) {...}
}

fire a function after triggering a click event

How can fix this :
function Navigation(sender) {
var senderID = sender.id;
var answer = confirm("do you want to save your current layout ?");
if (answer) {
$("#loadingImg").css("display", "block");
$("#<%=Button1.ClientID %>").click();
//the next line is never fired
if (senderID == "AboutClick") { setTimeout('ShowLoadingMsg()', 3000); }
}
}
function ShowLoadingMsg() {
window.location="About.aspx";
}
<a href="javascript:void(0)" id="AboutClick" class="menu" onclick="Navigation(this);" >Navigate Click</a>
<asp:Button ID="Button1" runat="server" OnClick="btnSaveState_Click" style="display:none;" />
//Server side:
protected void btnSaveState_Click(object sender, EventArgs e)
{
SaveState();
}
The main problem is that this line is never fired what am i doing wrong here
The problem here is that $("#<%=Button1.ClientID %>").click(); causes the entire page to reload. It won't really matter what scripts you set a timeout for after that, since the page is refreshed anyway.
You could try putting Button1 inside an UpdatePanel, or just solve the problem in another way, such as saving state and redirecting in the same method.
Try this:
Navigate Click​
-
$(function(){
$(".trigger").click(function(){
var answer = confirm("do you want to save your current layout ?");
if (answer) {
$("#loadingImg").show();
if (this.id == "AboutClick") { setTimeout('ShowLoadingMsg()', 3000); }
$("#<%=Button1.ClientID %>").click();
}
})
})
function ShowLoadingMsg() {
window.location="About.aspx";
}
Demo here!

Getting a form to submit from JavaScript?

I have a form in a JSP as follows:
<form action = "<c:url value = '/displayVisualisation' />"
title = "${item.visDescription}"
method = "post" onClick = "return confirmRequest('Do you want to change to
another visualisation type?');">
<input class = "text" type = "text" value = "${item.visTypeName}">
</form>
Which calls a Javascript method as follows:
function confirmRequest(questionText) {
var confirmRequest = confirm(questionText);
if (confirmRequest) {
return true;
}
else {
return false;
}
}
To ask the user for a reply to the question asked. However, the confirm prompt appears but does not perform the displayVisualisation action!
Can anyone suggest why or help me implement this correctly?
In other examples, where the action is triggered by clicking a graphic, all is well.
Since you are using onclick, return true; in your confirmRequest function is simply allowing the rest of the clickHandler chain to be executed. I think you also need to explicitly submit the form at this time, in the true case.
Here is one way to do that, using only javascript:
function confirmRequest(questionText) {
var confirmRequest = confirm(questionText);
if (confirmRequest) {
document.forms[0].submit();
return true;
}
else {
return false;
}
}

Categories

Resources