So I'm having some trouble. Even after trying many different solutions my problem is still persistent.
The button click will fire the java script code, but not the server side code.
<asp:Button ID="btnSubmit" runat="server" CssClass="ins_sub_btn_form_map" OnClientClick="javascript: stripeSubmit(); return true;" onClick="btnSubmit_Click"
UseSubmitBehavior="false" ValidationGroup="Submit" Text="Submit" />
here's my javascript:
function stripeResponseHandler(status, response) {
if (response.error) {
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#form1");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='visible' id='stripeToken' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
function stripeSubmit() {
Stripe.setPublishableKey($("input#txtStripePK").val());
var expDate = $("input#txtExpirationDate").val();
if (Stripe.card.validateCardNumber($("input#txtCreditCardNumber").val()) == false)
{
alert("Credit Card Number Error");
return;
}
if (Stripe.card.validateCVC($("input#txtCVVNumber").val()) == false) {
alert("CVN Number Error");
return;
}
if (Stripe.card.validateExpiry((expDate.slice(0, 2)) , ("20" + expDate.slice(2, 4))) == false) {
alert("Expiration Date Error");
return;
}
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.card.createToken({
number: $("input#txtCreditCardNumber").val(),
cvc: $("input#txtCVVNumber").val(),
exp_month: (expDate.slice(0, 2)),
exp_year: ("20" + expDate.slice(2, 4))
}, stripeResponseHandler);
//return true; // submit from callback
}
I've tried it without the return true in javascript, with it in javascript. Also tried it without the return true in the onClientClick, also without the "javascript:". Literally everything I can think of.
Any help is appreciated. Thanks in advance.
If I'm not mistaken, by default, asp control's UseSubmitBehavior property is set to true. This means any event performed on that control will cause a postback. You have UseSubmitBehavior set to false so the code behind will never get executed since no postback occurs. When using OnClientClick() and OnClick() together, the client side code will execute first and then the server side code. Hope this helps
Use closing () on the method inside your Onclick. ex onClick="SomeMethod()"
Related
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
I am working on a brownfield site that fires asp.net clientside validation, whatever the result it always does a postback. Has anybody any ideas to stop this behavior if it fails the validation?
Thanks in advance.
Podge
You can leverage Custom Validator control w3schools or MSDN link. It allows you to perform client side validation. Usage example.
<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckEven" /><br>
Input:
<asp:TextBox id="txtCustomData" runat="server" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
I was getting the same behavior and fixed it by setting the CausesValidation property to True.
just for example: validate the textbox , if its empty postback not called else postback called.
button click event:
<asp:TextBox id="vTextBox" runat="server" />
<asp:button id="okButton" runat="server OnClick="okButton_Click" OnClientClick=" return isValidate();"/>
<script type="text/javascript">
function isValidate() { var txt = $("#vTextBox").val();
if ( txt === "") { alert("error"); return false; }
else { alert(" no error "); return true; } }
</script>
In my case I had a couple of CustomValidators where the ClientValidationFunction was missing.
Ensure there are no JavaScript errors on the page which could also cause this problem.
For Client Validation you must be calling some JS function for validation:
If you are calling the client side validation method on a button click then you should call it like below:
<asp:Button runat="server" id ="btnSubmit" onClientClick="return ValidateForm();" >
And the Validate Form method should return true or false.
like :
function ValidateForm()
{
/// Validation goes here
if (validated)
{
return true;
}
else{
return false;
}
}
}
Basically we have the "illusion" of an notification message box that exists as .Visible = false in the MasterPage. When it comes time to display a message in the box, we run a method that looks like this:
public static void DisplayNotificationMessage(MasterPage master, string message)
{
if (Master.FindControl("divmsgpanel") != null)
{
master.FindControl("divmsgpanel").Visible = true;
}
if (master.FindControl("divdimmer") != null)
{
master.FindControl("divdimmer").Visible = true;
}
TextBox thetxtbox = (TextBox)master.FindControl("txtboxmsgcontents");
if (thetxtbox != null)
{
thetxtbox.Text = message;
}
}
Basically through our designers awesome CSS voodoo, we end up with what appears to be a floating message box as the rest of the page appears dimmed out. This message box has a "Close" button to dismiss the "popup" and restore the dimmer, returning the site to the "normal" visual state. We accomplish this with JavaScript in the MasterPage:
function HideMessage() {
document.getElementById("<%# divmsgpanel.ClientID %>").style.display = 'none';
document.getElementById("<%# divdimmer.ClientID %>").style.display = 'none';
return false;
}
and the button's declaration in the .aspx page calls this HideMessage() function OnClientClick:
<asp:Button ID="btnmsgcloser" runat="server" Text="Close" style="margin: 5px;"
OnClientClick="return HideMessage()" />
The problem:
All future postbacks cause the MasterPage to "remember" the state of those divs from how they were before the HideMessage() JavaScript was executed. So in other words, every single postback after the initial call of the DisplayNotificationMessage() method causes the page to return to divmsgpanel.Visible = true and divdimmer.Visible = true, creating an endlessly annoying message box that incorrectly pops up on every postback.
The question:
Since we want the Close function to stay client-side JavaScript, how can we "notify" the page to stop reverting to the old state on postback, for just these two divs?
Can you try setting them to Visible = false in Master_Page Load event? It should hide them and reshow them just when you call DisplayNotificationMessage
When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"
How can i get the value that was pressed in the confirm box?
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
if (confirm("Are you sure you want to proceed?")==true)
return true;
else
return false;
}
</script>
C#
Button2.Attributes.Add("onclick", "return confirm_proceed();");
Try this, if this is the only button that has this behavior
Button2.Attributes.Add("onclick", "return confirm('Are you sure you want to proceed?')");
it's inline and looks straightforward but if you have multiple controls that behave this way then your original approach would be easy to maintain.
And your original function could be shrunken to
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
return confirm("Are you sure you want to proceed?");
}
</script>
You can store the value of confirm_proceed() in an asp:HiddenField
You can modify your script as follows:
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
var hiddenField = document.getElementById('hiddenFieldId');
if (confirm("Are you sure you want to proceed?")==true)
{
hiddenField.value = 'true';
return true;
}
else
{
hiddenField.value = 'false';
return false;
}
}
</script>
You can now access first the hidden field's value in your Button2_Click event.
I just face similar problem in a real production project and I solved it by the following:
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" onClientClick="return confirm('Are you sure you want to proceed?')"/>
so the OnClientClick Client event is raised befoere the onClick which is a server event , so if the user clicks OK then the Client event returns True from the confirm Dialog and therefore the Code Behind this button is executed , on the other hand if the user clicks (Cancel or No) then it would return false and therefore the code behind wont get exected (Server Event is Cancelled)
hope it would help you as I really applied it to my project and worked without any issues.