I have a button within a form. The thing is when I click it, it does not execute the server side function. Is it possible to prevent form submission, while executing server functions and client side validations ?
Thanks in advance.
html (inside a form)
<button class="submit" runat="server" id="v4" onserverclick="v4_Click" >Validate</button>
jquery
$('#v4').click(function (event) {
if (validation()) {
slideToStep(5);
}
return false;
});
c#
protected void v4_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Debug.Write("test");
}
I believe you can achieve what you're wanting, by binding the event.preventDefault()
to the submit
event of the form, rather than the click
event of the button.
Setup an onclick
for your button to call a function that submits your form.
<button class="submit" id="v4" onclick="SubmitForm();" runat="server" onserverclick="v4_Click" >Validate</button>
Set the SubmitForm()
function to submit the form, then bind a function to your submit event:
function SubmitForm() { $('#form1').submit(); } $(function () { $('#form1').submit(function (event) { if (validation()) { slideToStep(5); } else { //Validation Failed, prevent form from submitting. event.preventDefault(); } }); });
Is it possible to prevent form submission
yes it is you can simply write e.preventDefault()/Return false()
on jquery click of button
But again While using server side function
i am not getting this
The problem is in your javascript code, in your case return false
is always called, instead you should only call it when your validation fails:
$('#v4').click(function (event) {
if (validation()) {
slideToStep(5);
} else{
return false;
}
});
Edit:
Basically, if you want to call the button_click event, you need to submit the form, in your case I would use a WebMethod
to call a server side validation function with ajax. Something like this:
c#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Validate(string params)
{
// your validations
return "Received : " + params;
}
jquery:
$(document).ready(function() {
$("#v4").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/Validate",
data: "{params: 5 }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
Alternative:
You could also use a customValidator, and ASP will do all of the jquery stuff for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.