ASP.Net LinkButton Prevent Postback Not Working - JavaScript - javascript

I know how to prevent javscript within the href attribute from firing as evident in this JSFiddle (http://jsfiddle.net/mkarr/KNefK/)
However, when this logic is applied to an ASP.Net LinkButton as such:
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return formTest.validate(event);" OnClick="btnSubmit_Click"></asp:LinkButton>
which translates to:
<a onclick="return formTest.validate(event);" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmit" href="javascript:WebForm_DoPostBackWithOptions('blah blah blah')">Submit</a>
The formTest.validate() method does execute correctly and returns false, but the WebForm_DoPostBackWithOptions is always fired immediately after!
Can anyone see any flaws in my logic that I cannot??
EDIT:
Also, several stack overflow solutions have been accepted for this issue but all of them are doing virtually what I have already done leading me to believe I'm missing something simple!
Disable the postback on an <ASP:LinkButton>
Prevent LinkButton post back OnClientClick not working. Why?
ANSWER:
Since I cannot answer my own question because I'm not reputable yet (LOL), here's an edit with the answer:
Going off #QBM5's original tip of not using ASP.Net controls, I solve the problem, although I still do not know why the initial problem occurred in the first place (does anyone when it comes to ASP.Net? Turn it off, then back on comes to mind here) :o)
I replaced the LinkButton ASP.Net control with the following:
<input type="submit" value="Submit" id="btnSubmitButton" runat="server" OnServerClick="btnSubmitButton_Click" class="submitBtn" />
I then bound the .submitBtn's click event via jQuery:
$('.submitBtn').on('click', function (e) {
if (!instance.validate()) {
e.preventDefault();
}
});
The trick is to use OnServerClick and runat="server" on the control but getting away from LinkButton was the goal and the postback behavior is completely different.
which translates to this:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); " type="submit" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmitButton" value="Submit" class="submitBtn">
Anyone want to take a stab at the root cause? I need to move foward so don't have time. :o)

The following is working for me, by changing element.href = "#"
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return ClientSideValidation()" OnClick="btnSubmit_Click"></asp:LinkButton>
Javascript validation
function ClientSideValidation() {
var element = document.getElementById("<%=txtAmount.ClientID%>");
element.href = "";
if (element.value == "") {
element.href = "#";
return false;
}
return true;
}

Related

How to disable link button after click (no JQuery)

I want to disable link button after user click on it.
But I made something wrong here.
Button is still enabled after click. What am I doing wrong?
<asp:LinkButton ID="submit" runat="server"
CssClass="button"
Text="OK"
OnClick="Submit_Click"
OnClientClick="this.disabled=true">
</asp:LinkButton>
Just give return false; to your JavaScript. The reason is that your asp:LinkButton is getting rendered like this.
<a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$submit','')"
class="button"
id="ContentPlaceHolder1_submit"
onclick="this.disabled = true;return false;">
OK</a>
So, if you do not give return false, these things happens
It fires the onclick event and disables the anchor tag. (anchor tag does not have a disabled property. button and input type="submit" has that property.)
It moves on to fire the postback and hits the server side click event
As there is a postback, the client side JavaScript disabling wont persist (even if it were a button)
By enforcing return false you are asking the asp:LinkButton not to do anymore processing.
P.S: I have been using PostBack Ritalin to prevent multiple clicks on asp:Button. IMO, its definitely worth a look in this case.
Use the javascript debugger to check the method is being called. LinkButtons are server generated javascript powered anchor tags & therefore can be tricky.
Try this java script function ,
On your OnClientClick
<asp:LinkButton ID="submit" CssClass="button" Text="OK" onclick="myButtonId_Click(this);return false;" ></asp:LinkButton>
add function ,
protected void myButtonId_Click(target) {
target.disabled = true;
}

BUTTON ONCLICK ONSERVERCLICK

I am facing a problem with buttons.
I want a client side validation to occur(say selecting a maximum of only 4 checkboxes in a datalist).
I used a INPUT TYPE="BUTTON" RUNAT="SERVER" style of tag. and put Onserverclick="someservermethod" which works fine.
I wrote a Validate() and added onclick="return validate();" to the above HTML markup and was thinking if it returns false then my server side code someservermethod() would not execute and it works great as expected
But when I return true I thought it would fire my someservermethod(), but it is not working. Any thoughts on why it is not working?
HTML MARKUP BELOW FOR THE BUTTON
button onclick="return ValidateSelection();" type="button" id="btnSubmit"
runat="server" onserverclick="btnSubmit_Click"
JAVASCRIPT CODE
function ValidateSelection()
{
if(good)
{
// I expect that my server side code btn_Submit would have got called. But
// it doesn't get called.
return true;
}
else
{
//This works great. Not calling the server side method for the button
alert('something happened');
return false;
}
}
I think I am messing up with the formatting. Pardon me.
The control you are using right now it HtmlButton which is not "fit" for what you are trying to do, as your onclick overwrites the required client side code for the post back.
What you need is the Button control which does support overwriting the client side onclick and still perform the post back as usual.
Change the markup to this and it should work:
<asp:button OnClientClick="return ValidateSelection();" id="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit"></asp:Button>

How to fire a button click event from JavaScript in ASP.NET

How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.

Adding javascript from code breaks the validation on page! How to handle it?

What I have is button that should open another page only if textbox length is 8. Javascript must be added from code because it does not simply calls the bla.aspx, it's more like bla.aspx?id=4&code=234 etc etc...
I have this code on server side
button.Attributes.Add("onclick","javascript:window.open(bla.aspx)");
on client side i have
<asp:TextBox ID="policyNumberTxt" runat="server" MaxLength="8" CausesValidation="true"></asp:TextBox>
<asp:RegularExpressionValidator ID="policyNumberTxtRev" runat="server"
ControlToValidate="policyNumberTxt" ErrorMessage="Length must be 8."
ValidationExpression="{.{8}.}" ValidationGroup="bla" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:Button ID="printBtn" CssClass="button" Text="Print" runat="server" CausesValidation="true" ValidationGroup="bla" />
What happens is that when I click the button page bla.aspx opens, and even postback is trigered. Validator is showing the message, but page is opened and postback trigered.
How to handle this? Validation is broken...
Thanks..
To prevent submitting the form add "return false;"
button.Attributes.Add("onclick", "window.open('bla.aspx'); return false;")
but that would also prevent the form from doing postback at all!
note that the passed url should be enclosed in quotes..
And you don't need the "javascript:" prefix as 'Pointy' said
I think the validation regular expression should be more strict to allow only letters and numbers like this
ValidationExpression="[A-Za-z0-9]{8}"
Try putting the client click logic in the onsubmit of the page's form instead?
Found answer here
this.cmdSubmit.Attributes.Add("onclick","if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();if(Page_IsValid){window.open('upload_status.aspx','_blank','width=250,height=250');}");

How to...Add Client Side function to button that postsback?

I have a button that closes a modal dialog box on an ASP.NET Ajax form. How do a add a client side function to be called on the same button click?
currently firebug has this for the onclick
javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$DefaultContent$btnPaymentActionDetailClose", "", true, "", "", false, false))
can I just add a click handler with jQuery? I don't want to wipe out the postback as it is necessary for the forms functionality.
Can I use
$("#buttonId").bind("click", function(e){
runAnotherFunction();
});
And not interfere with the existing postback?
Actually truth be told, I want to exec the function when the modal dialog closes. Do ajax control toolkit widgets fire any type of events? I know I can find the behavior and call show and hide. Can I attach my function to exec when modal.hide() is executed?
Thanks for any advice,
~ck in San Diego
Yes, you can definitely have your ASP:Button run Javascript on the client before posting back. It's the OnClientClick property of the webcontrol.
You won't need jQuery for this.
<asp:button id="btn" runat="server" onClientClick="SomeJsFunction()"
onClick="ServerSideMethod()" Text="Hello Button" />
<script language='javascript'>
function SomeJsFunction()
{
alert('hi');
}
</script>
If you're interested controlling whether the postback occurs or not, you could return and check for true/false from the result of your Javascript function.
function SomeJsFunction()
{
var isGood = false;
return isGood;
}
<asp:button id="btn" runat="server" onClientClick="return SomeJsFunction()"
onClick="ServerSideMethod()" Text="Hello Button" />
(thanks to Ralph for the nudge in the comments)

Categories

Resources