Form submit not posting back on ASP.NET page - javascript

I have a form in ASP.NET with this button:
<asp:Button ID="btnNext"
runat="server"
CausesValidation="false"
Text="Submit Form" />
I do validation on this form with jQuery Validate, like so:
jQuery(function() {
jQuery('#form1').validate({
rules: {
txtSerialNumber: {
required: true
}
},
messages: {
txtSerialNumber: {
required: "Please enter a serial number."
}
}
});
});
There's more, but it's the same for all the fields. I have verified that this validation code works.
I also have some javascript to call the validation code, since it was not working before (for various reasons).
jQuery('#btnNext').on("click", function () {
if (jQuery("#form1").valid()) {
jQuery(this).prop('disabled', true); // prevent multiple submits
return true;
} else {
return false;
}
});
Edit: When I comment out the line that disables the button, the form gets submitted correctly. So it seems like disabling a submit button before the page posts back causes the page to not post back.
When I click on this button to submit the form, the javascript above gets called, but the page doesn't post back and submit. I've been pulling my hair out trying to get this figured out. Is there an obvious reason that it's not working correctly? What am I missing?

Add a OnClientClick event to the button, which is going to call the validation, instead of adding the .on("click") event handler with jquery.
<asp:Button ID="btnNext"
runat="server"
CausesValidation="false"
Text="Submit Form"
OnClientClick="validate()" />
javascript:
function validate () {
if (jQuery("#form1").valid()) {
jQuery(this).prop('disabled', true); // prevent multiple submits
return true;
} else {
return false;
}
});

Related

How can I run jQuery script before form submit without using OnClientClick

I have an ASP.Net WebForms application where I am using jQuery validation. There are several buttons to submit the form, each with different options on the back end.
I have a custom validateForm() function that I can assign to the OnClientClick event of all the buttons, but I'm hoping for a more elegant solution where I don't have to specifically give each button the OnClientClick property.
So basically, is it possible to capture the $(form).submit() event before an asp button is submitted? Without using the OnClientClick attribute?
Solved: My issue was actually not because I couldn't catch the submit, but because the buttons were <a> links instead of inputs. I didn't realize this and made the post while at home trying to fix it from memory.
Any of the below solutions should work in the scenario above with actual submit buttons
Just attach a listener to the submit event:
$('form').on('submit', function (event) {
// Do whatever you need to do here ...
// You could also do `event.preventDefault();`,
// if you wanted to stop the submit.
});
You can use onsubmit event that will execute a JavaScript when a form is submitted from any button.
<form id="form1" runat="server" onsubmit="return ValidationFunction();">
And your JS function should return true or false as
function ValidationFunction() {
// Your jQuery validation
if (isValide) {
return true;
}
else {
return false;
}
}
Another option using JQuery to attaches an event handler to form submission
$(document).ready(function () { // << to make sure DOM is loaded
$('#form1').on('submit', function (e) {
e.preventDefault(); // << the default action of the event will not be triggered
var isValide = false;
if (isValide) {
alert('ok');
this.submit();
}
else {
alert('Not Valid');
}
});
});

Access the value assigned to the clicked submit button with JavaScript

I noticed one pecular thing. When there are several submit buttons in your HTML form like so:
<button type="submit" name="submit_button", value="b1"></button>
<button type="submit" name="submit_button", value="b2"></button>
<button type="submit" name="submit_button", value="b2"></button>
..and you do this:
var $form = $('#my_html_form');
$form.submit(function() {
if (!checkPassed && !hasRequiredValue) {
bootbox.confirm('Are you sure that you don\'t need <strong>{requiredValue}</strong> parameter?', function(result) {
if (result) {
checkPassed = true;
$form.submit();
}
});
return false;
}
});
the field submit_button does not get submitted at all, it's just not present in the request data.
Would there be a way to force JS to submit data together with the value of the submit button clicked?
I will only add that if the form is submited with PHP and not JS, the submit_button field is present and has the value of b1, b2, or b3 - depending on which button was clicked.
P.S. I just thought that the source of the problem might be that I'm using <button> instead of <input>. However, as I said, it's all good with PHP.
Only a successful submit button will be included in the form data.
A successful submit button is one that is used to submit the form.
Your JavaScript runs on the submit event and:
Always cancels the submission of the form
Sometimes submits the form with JS
Since you are submitting the form with JS instead of the submit button, none of the submit buttons are successful.
Change your JS so that it:
Sometimes cancels the submission of the form
Such:
$form.submit(function() {
// Add a NOT condition here
if (!<someCondition>) {
return false;
}
return true;
});
Regarding the update:
OK, so you are always canceling the submission, and using a DOM based widget to ask for confirmation.
In that case, you need to capture the value of the submit button separately.
The information isn't exposed to the submit event so you need to do it on the click event of the submit button.
Add a hidden input to your form:
<input type="hidden" name="submit_button">
Then add another event handler:
$form.on("click", '[name="submit_button"]', function (event) {
$form.find('[type="hidden"][name="submit_button"]').val(
$(this).val()
);
});
Yes you can get the value of the button
$('button').click(function(event) {
var button = $(this).data('clicked', $(event.target));
var value = button.val();
});
Here you go.
$("button[name=submit_button]").click(function() {
alert($(this).val());
});
Fiddle: http://jsfiddle.net/tw698hvs/

html5 validation error message without submitting form

I am developing an app in which I am using HTML5 fields in my form. I want to trigger html5 field validation on button click for this purpose I have written this code
<input type="button" id="btnContactSubmit" class="btn btn-success" value="Submit">
$('#btnContactSubmit').click(function (e) {
if ($('#aspnetForm')[0].checkValidity()) {
e.preventDefault();
if (flag) {
createListItem();
}
} else {
e.preventDefault();
}
});
button click is working fine but it doesnot showing error message on relevant field I want to show error message without submitting my form.
There is no way to trigger the native tooltips other than submitting the form.
If the form is valid, prevent it from submitting, and if it's not valid, just submit it, and the native HTML5 validation will happen, but the form won't be submitted anyway.
You are preventing the default action in both conditions, so the validation never happens, do it like this, and it will
$('#btnContactSubmit').click(function (e) {
if ($('#aspnetForm')[0].checkValidity()) {
e.preventDefault();
if (flag) {
createListItem();
}
}
});
FIDDLE

stop asp.net btnsave.click event from firing when validation fails

I have this java script validation function that fires when the client clicks btnsave
if the text of the text box is empty then a message box is displayed and the focus is on the
text box but i cannot seem to prevent the page from posting back when the validation fails
AM I missing something. here is my code
function validate()
{
var itemscanned;
itemscanned = document.getElementById('txtItemCode');
if (itemscanned.value == '')
{
alert("Plz Enter Item Code");
return false;
itemscanned.focus
}
else
{
alert(itemscanned.value);
}
}
Write return before function name like this
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="buttons" OnClientClick="return validate()"/>
If this is an ASP.NET WebForms application, you really should consider using the Validator controls. They handle all of client-side logic you are asking for.
If you are using MVC, there is also a way to do model validation on the client side.
add this if its asp.net button control
OnClientClick = "return validate();"
if it is html button add this
onclick = "return validate();"
Ît belongs how you handle the events. Please show the asp markup and the binding of the javascript event.
You can try to stop event propagation using javascript:
event.stopPropagation();
Read about it here: https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
Note: you have to get the event as an parameter to the validate function:
function validate(event) {
var itemscanned;
itemscanned = document.getElementById('txtItemCode');
if (itemscanned.value == '') {
alert("Plz Enter Item Code");
event.stopPropagation();
itemscanned.focus
return false;
}
else
{
alert(itemscanned.value);
}
}​
Hope this helps. It's very important how you bind the validate function the button, because asp.net generates a lot of javascript on its own (google for asp.net client validation).

Disable Button placed inside an ASP.NET template upon click using Javascript

I hava an ASP.NET Web Forms application.
My goal is to disable the submit button btnFinish upon user click, in order to avoid multiple submits.
<asp:Button ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The Javascript function is:
function Validate(btnFinishId) {
btnObj = document.getElementById(btnFinishId)
if (Page_IsValid) {
btnObj.disabled = true
}
else {
alert('Page has some validation error');
}
// this is to prevent the actual submit
e.preventDefault();
return false;
};
btnFinish is placed within a FinishNavigationTemplate in a ASP.NET Wizard Control.
Therefore, in order to avoid runtime errors, I need to get the ClientID of the control programmatically and then add it to the OnClientClick event of the button:
Button btFinish = MyWizard.FindControl("FinishNavigationTemplateContainerID$btnFinish") as Button;
if (btFinish != null){
btFinish.Attributes.Add("onclientclick", "Validate('" + btFinish.ClientID + "');");
}
But it does not work. I use Firebug to check the page rendered by the browser but although the source code looks perfect, upon click the Javascript function is not executed.
If in the Javascript function I replace Validate(btnFinishId) with Validate() and instead of using the code behind to add the OnClientClick I write:
<asp:Button OnClientClick="Validate();" "ID="btnFinish" runat="server" Text="Finish" UseSubmitBehavior="false"
CausesValidation="true" CommandName="MoveComplete" CssClass="buttonStyle"/>
The function is executed but of course does not do what I want, because the button Id is missing. Anybody has a solution?
You're on the right track. Something like this should work:
<script type="text/javascript">
validate = function(btn){
//trigger client-side validation
var valid = Page_ClientValidate("");
//disable the button if the form is valid
btn.disabled = valid;
//trigger postback if the form is valid
//otherwise do nothing
return valid;
}
</script>
<asp:Button ID="btnFinish" runat="server" Text="Finish" OnClientClick="return validate(this);" OnClick="btnFinish_Click" ... />
It looks kind of backwards, but you could shorten the function like this:
<script type="text/javascript">
validate = function(btn){
btn.disabled = Page_ClientValidate("");
return btn.disabled;
}
</script>
One way is to create a normal HTML button on your page, add attach a click event with jQuery.
You can then hide the .net button using css.
In the click event for your html buttom, you can all the .net buttons click event.
$("#yourbutton").trigger("click");

Categories