Trigger JavaScript Confirm() from code behind - javascript

I am working on a Asp.Net application, currently i am trying to trigger a JavaScript Confirm() popup from the code behind. I would like to popup without clicking any button_click event.
IF not blnResult then
popup message with OK& CANCEL
IF OK THEN Exit Sub
ELSE
no display
END IF
I tried to do below things and it's not firing popup, please assist.
1) Created a button in ASPX
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm()"/>
JavaScript function
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
}
</script>
Code behind,
Public function GetConfirmation()
btnConfirm_Click(btnConfirm, EventArgs.Empty)
End Sub
Above line isn't firing the popup for me.

If I have understood correctly then probably you want to call your code behind click event only when user confirms by click on yes. There are many of ways doing this. I have listed few of them. Choose which ever suits best for you.
Don't know why you have created a hidden input field. What is the purpose of creating it. In case you don't need hidden input filed you can try these out.
Confirmation in HTML Tag
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="return confirm('Do you want to delete all records?');"/>
Confirmation in JavaScript
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm();"/>
<script language="javascript" type="text/javascript">
function Confirm() {
return confirm("Do you want to delete all records?");
}
</script>
Or
<script language="javascript" type="text/javascript">
function Confirm() {
var result = confirm("Do you want to delete all records?");
return result;
}
</script>
If you do need to keep hidden input field then use below.
<script language="javascript" type="text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
var result = confirm("Do you want to delete all records?");
confirm_value1.value = result ? "Yes" : "No";
document.forms[0].appendChild(confirm_value1);
return result;
}
</script>

Just modify your javascript function.
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
return false;//this will prevent submit click.
} </script>
just add return statement at last line of function.
return false;
I hope this solution will help you.

Related

sweet alert message in JavaScript is showing for a split second

When user press confirm button,
i need to check a few things using javascript and in a certain condition need to show sweet alert
in which, once the user will press ok (in the sweetalert message) it will redirect to another page.
but the alert is showing for a split second and not redirecting to the page(since i didnt press "ok").
javascript is called from onClick of a button in the view:
<div class="col">
<button type="submit" class="btn btn-primary form-control" onclick="ApprovePayment()">Create</button>
</div>
here is the javascript in the view :
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment() {
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}
The onclick listner is defined on the submit button, when you click on the submit button the browser will perform the default action which is the form submit.
To prevent this you can use two approaches.
Add the listener on the form onsubmit.
Prevent the browser default action.
Change the button type from submit to 'button'.
Example for the second method.
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment(event) {
event.preventDefault(); // stop the default action
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}

Javascript Function Not Firing from C# Function ASP.Net

I am using a asp:Repeater control while trying to develop a screen as shown below:
Submit form
When ToolId is entered on the TextChanged Event I am getting value for MaxToolLife stored as double. When an user enter values greater than the stored value for the field ToolLife I need to show Yes/No popup stating "The value entered is greater than existing value. Do you want to proceed?" on button submit or textchanged event.
Currently I am using the below code but I am not getting Javascript alert.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Convert.ToDouble(txtToolLifeAchieved.Text) > maxToolLife)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Confirm", "javascript:Confirm();", true);
if (hdnconfirm.Value=="Yes")
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
else
{
txtToolLifeAchieved.Text = "1";
txtToolLifeAchieved.Focus();
return;
}
}
else
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
}
In place of Page.ClientScript I have also used "Page.ClientScript.RegisterClientScriptBlock" & /ScriptManager.RegisterStartupScript. Nothing is working as of now. I am unable to call the javascript function from code behind. Any immediate response would help a lot.
The confirm() is as shown below:
function Confirm()
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("The data already exists. Do you want to Overwrite data?"))
{
confirm_value.value = "Yes";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else
{
confirm_value.value = "No";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
document.forms[0].appendChild(confirm_value);
}
So, I will stick to your original code, and this is how your server method should look like:
// This is just to illustrate the limit
private const double MaxToolLife = 100;
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check the limit first
if (Convert.ToDouble(txtToolLifeAchieved.Text) > MaxToolLife)
{
// If the hidden field is empty show the confirm
// By default the hidden field is empty, it means that user just
// pressed the submit button but not the confirmation dialog
if (string.IsNullOrWhiteSpace(hdnconfirm.Value))
{
ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "Confirm();", true);
return;
}
// If the hidden field is not empty, this postback was made by the confirm
// So check for the value of the hidden field
if (hdnconfirm.Value == "Yes")
{
// Handle 'Yes'
}
else
{
// Handle 'No'
}
}
else
{
// The limit is not reached
}
}
I omitted your specific code above. This is how the form looks like:
<form id="form1" runat="server">
<!-- Hidden field for the confirm result -->
<asp:HiddenField ID="hdnconfirm" runat="server" />
<!-- Text box for user input -->
<asp:TextBox ID="txtToolLifeAchieved" runat="server"></asp:TextBox>
<!-- Submit button -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
Than right before the form tag in your page, place your javascript function, it must be place before the form tag, because calling ClientScript.RegisterStartupScript will append the script at the end of your form tag and that time your Confirm() method be defined. And this is your javascript method:
<script type="text/javascript">
function Confirm() {
if (confirm("The data already exists. Do you want to Overwrite data?")) {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
// Post the form back to server using the '__EVENTTARGET' hidden field
var form = document.getElementById("form1");
// Create hidden field
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "__EVENTTARGET");
input.setAttribute("id", "__EVENTTARGET");
input.setAttribute("value", '<%= btnSubmit.ClientID %>');
// Append input to the form element
form.appendChild(input);
// Submit the form
form.submit();
}
</script>
There is no need to create another hidden field for the confirmation result. Instead just right after the confirm you need to create hidden field with name set to __EVENTTARGET, and the value of that hidden field must be the name of the submit button, and than just call submit method on the form. This will case postback to the server, with the hdnconfirm set to Yes or No while your btnSubmit_Click method will be executed.

How to display confirm box on website in php

i want to display an confirm box with two button yes and no, when user press yes than index page will be displayed and when user press no this redirect to another page. this confirm msgbox display only once when first time website open not on every reloading of page. Thanks
you can try this code
<script>
var confirm = confirm("sample message?");
if(confirm) {
// index page
window.location.url = ""; // your url index page
} else {
// other page
window.location.url = ""; // your url other page
}
</script>
You have to do all stuff in javascript.
Javascript Function you can use.
Also you need to set cookie at browser and check if cookie is set.
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
Hope this helps.
function myFunction() {
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<html>
<head>
<title>Are you sure?</title>
<script>
function areYouSure() {
var res = confirm("Are you sure?");
return res; //true or false
}
</script>
</head>
<body>
<form method="POST" action="action_page.php">
<!--
...
-->
<input type="submit" onclick="return areYouSure()"/>
</form>
</body>
</html>

Click button. Javascript alert box. If click OK, page reloads and need to create php variable with html input form value

User clicks on Delete button. Javascript alert box popups with OK and Cancel. If user clicks OK, then page reloads (post form) and I need to create php variable with value from here name="confirm_delete")
Here is my code
<form action="<?php echo (htmlspecialchars($_SERVER["PHP_SELF"])) ?>" method="post">
<input name="delete" type="submit" id="delete" value="Delete">
<input type="hidden" name="confirm_delete" id="confirm_delete" value="0" >
<script>
$(document).ready(function() {
$("#delete").click(function(){
var answer = confirm("Are you sure you want to delete?");
if (answer){
return true;
document.getElementById('confirm_delete').value = 1;
} else {
return false;
document.getElementById('confirm_delete').value = 0;
}
});
});
</script>
Then print_r($_POST['confirm_delete']); but value always is 0. That means that document.getElementById('confirm_delete').value = 1; does not work.
Please, advice what need to correct
Replace your javascript code by following:
<script>
$(document).ready(function() {
$("#delete").click(function(){
var answer = confirm("Are you sure you want to delete?");
if (answer){
document.getElementById('confirm_delete').value = 1;
return true;
} else {
document.getElementById('confirm_delete').value = 0;
return false;
}
});
});
</script>
You are using the return true and false first after that you are assigning the value. so return terminates from the function before assign the value. so first assign the value and then use the return.

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1), i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.
So i was trying to accomplish it using Javascript Confirm function
var r = Confirm('Do you want to overwrite ?)
but now i have to capture this Var r into my page so that i can update my database accordingly
any help how can i do it ?
On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.
Just have something like this:
<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />
If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.
Here is your code:-
Add a hidden field in Net(.aspx) page
<form id="form10" runat="server">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
</form>
The hidden field should be added under Form Tag.The value of this hidden field is initially "false".
Here is what you need to do in Code Behind file (.cs file)
protected void btnSubmits_Click(object sender, EventArgs e)
{
if (hdnField.Value == "false")
{
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
Here is the code to capture the response from OK/Confirm or Cancel button.
private void AddJavascriptCode(string itemValue)
{
string script = #"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + #"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + #"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + #" value. Do you want to overwrite ?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
Hope this helps you :).

Categories

Resources