How to avoid form submission in case of error? - javascript

I have the form like below
<form id="myform" class="form-horizontal" class="collapse in">
<fieldset>
<!-- form fields are here -->
<div class="form-actions">
<button class="btn btn-inverse" id="search" name="search" data-loading-text="Searching...">Search</button>
</div>
</fieldset>
</form>
And I use the following code to act once button is pressed:
$("#search").click(function() {
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}
});
But if my javascript contains syntax errors, then the form is submitted regardless of try .. finally. How can I fix that? The form should be never submitted automatically.

Set the button type to "button".
button: The button has no default behavior. It can have client-side
scripts associated with the element's events, which are triggered when
the events occur.
<button type="button"...>Search</button>
The form won't submit at all if that is the case until you tell it to explicitly submit via Javascript.
See HTML5 specs for this simple solution. http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#attr-button-type

Set the action of the form to something that isn't correct, like action="error.html". Then as the final step in the form submit process, dynamically set the action to the correct link.
You can also make the button not submit at all, and submit the form manually:
$('#myForm').submit();

Use event.preventDefault at the beginning of the event and trigger the submit yourself.
$("#search").click(function(event) {
event.preventDefault();
// some javascript with syntax error is here
var foo = "bar";
alert(foobar); // ERROR
// if syntax error occurs in this scope, the form won't submit
$(this).closest("form")[0].submit();
});
DEMO

$("#search").click(function(e) {
e.preventDefault();
try {
// some javascript with syntax error is here
} finally {
return false; // don't submit form automatically
}});
on the click function, prevent the default action. Then if the code does pass, then manually call the submit
$('#myForm').submit();

Related

Problem when calling ajax for button onclick, nothing happens [duplicate]

I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:
If I remove the ng-click, the button doesn’t cause a page refresh.
If I comment out the code in the function, it doesn’t cause a page refresh.
If I change the button tag to an anchor tag (<a>) with href="", then it doesn’t cause a refresh.
The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.
Here is the form:
<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
<fieldset>
<div class="control-group">
<label class="control-label" for="passwordButton">Password</label>
<div class="controls">
<button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
</div>
</div>
<div class="buttonBar">
<button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
</div>
</fieldset>
</form>
Here is the controller method:
$scope.showChangePassword = function() {
$scope.selectedLink = "changePassword";
};
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button' when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
You can try to prevent default handler:
html:
<button ng-click="saveUser($event)">
js:
$scope.saveUser = function (event) {
event.preventDefault();
// your code
}
You should declare the attribute ng-submit={expression} in your <form> tag.
From the ngSubmit docs
http://docs.angularjs.org/api/ng.directive:ngSubmit
Enables binding angular expressions to onsubmit events.
Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).
I use directive to prevent default behaviour:
module.directive('preventDefault', function() {
return function(scope, element, attrs) {
angular.element(element).bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
});
And then, in html:
<button class="secondaryButton" prevent-default>Secondary action</button>
This directive can also be used with <a> and all other tags
You can keep <button type="submit">, but must remove the attribute action="" of <form>.
I wonder why nobody proposed the possibly simplest solution:
don't use a <form>
A <whatever ng-form> does IMHO a better job and without an HTML form, there's nothing to be submitted by the browser itself. Which is exactly the right behavior when using angular.
Add action to your form.
<form action="#">
This answer may not be directly related to the question. It's just for the case when you submit the form using scripts.
According to ng-submit code
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
formElement[0].addEventListener('submit', handleFormSubmission);
It adds submit event listener on the form.
But submit event handler wouldn't be called when submit is initiated by calling form.submit(). In this case, ng-submit will not prevent the default action, you have to call preventDefault yourself in ng-submit handler;
To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).
See Form submitted using submit() from a link cannot be caught by onsubmit handler
I also had the same problem, but gladelly I fixed this by changing the type like from type="submit" to type="button" and it worked.
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
Just add the FormsModule in the imports array of app.module.ts file,
and add import { FormsModule } from '#angular/forms'; at the top of this file...this will work.

Not sure why I can't get javascript to display answer to a calculation [duplicate]

I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:
If I remove the ng-click, the button doesn’t cause a page refresh.
If I comment out the code in the function, it doesn’t cause a page refresh.
If I change the button tag to an anchor tag (<a>) with href="", then it doesn’t cause a refresh.
The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.
Here is the form:
<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
<fieldset>
<div class="control-group">
<label class="control-label" for="passwordButton">Password</label>
<div class="controls">
<button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
</div>
</div>
<div class="buttonBar">
<button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
</div>
</fieldset>
</form>
Here is the controller method:
$scope.showChangePassword = function() {
$scope.selectedLink = "changePassword";
};
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button' when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
You can try to prevent default handler:
html:
<button ng-click="saveUser($event)">
js:
$scope.saveUser = function (event) {
event.preventDefault();
// your code
}
You should declare the attribute ng-submit={expression} in your <form> tag.
From the ngSubmit docs
http://docs.angularjs.org/api/ng.directive:ngSubmit
Enables binding angular expressions to onsubmit events.
Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).
I use directive to prevent default behaviour:
module.directive('preventDefault', function() {
return function(scope, element, attrs) {
angular.element(element).bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
});
And then, in html:
<button class="secondaryButton" prevent-default>Secondary action</button>
This directive can also be used with <a> and all other tags
You can keep <button type="submit">, but must remove the attribute action="" of <form>.
I wonder why nobody proposed the possibly simplest solution:
don't use a <form>
A <whatever ng-form> does IMHO a better job and without an HTML form, there's nothing to be submitted by the browser itself. Which is exactly the right behavior when using angular.
Add action to your form.
<form action="#">
This answer may not be directly related to the question. It's just for the case when you submit the form using scripts.
According to ng-submit code
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
formElement[0].addEventListener('submit', handleFormSubmission);
It adds submit event listener on the form.
But submit event handler wouldn't be called when submit is initiated by calling form.submit(). In this case, ng-submit will not prevent the default action, you have to call preventDefault yourself in ng-submit handler;
To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).
See Form submitted using submit() from a link cannot be caught by onsubmit handler
I also had the same problem, but gladelly I fixed this by changing the type like from type="submit" to type="button" and it worked.
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
Just add the FormsModule in the imports array of app.module.ts file,
and add import { FormsModule } from '#angular/forms'; at the top of this file...this will work.

Run JavaScript and php on one button

Can we run a js function on a submit button and php on the same button. I have a submit button that sends form data to a database using php, but I want a second action (JavaScript function) to take place once the button is clicked as well. Is that possible?
You can add onclick() event to submit button. it will execute before submitting the form.
var buttonClick = () => {
alert("Do what you want to do!"); // Add your second work here
}
<form action="yourfile.php">
<input type="submit" onclick="buttonClick();">
</form>
The correct method is to call the javascript function on the onsubmit attribute in the form with a return state. Thus the form will wait until the JavaScript returns true before proceeding with submit.
The HTML
<form action="something.php" onsubmit="return someJsFunction()">
<!-- form elements -->
<input type="submit" value="submit">
</form>
The JavaScript
function someJsFunction(){
//your validations or code
if(condition == false){
return false; // This will prevent the Form from submitting and lets
// you show error message or do some actions
}else{
return true; // this will submit the form and handle the control to php.
}
}
You can do this with the jQuery submit callback for this
$("form").submit(function(){
alert("Submitted");
});
see. https://www.w3schools.com/jquery/event_submit.asp

Unable to submit form using Javascript

I am trying to submit my form named 'vform' by using javascript and ajax.Here
Button named 'show' is being used to show the 'div' containing form named vform and that form calls codevalidate function and there it submits the form using some ajax code..Where i am getting error is vform.submit().Here's the html and js code(I know error is in if condition but do not know where)
html:
<button id="show" onClick="javascript:codefield(); return false";>Apply for Discount</button>
<div id="apply" style="display:none">Voucher code<br>
<form id="vform" name="vform" action="" method="post" onsubmit="javascript:codevalidate(); return false;" >
<input type="text" name="code" id="code"><br>
<span id="error" style="color:red"></span><br>
<input type="submit" name="btn" value="apply" id="btn" ></form>
</div>
javascript:
function codevalidate()
{
if(document.getElementById('code').value!=="")
{
$.post("couponajax.php",{code:$("#code").val()},
function(data)
{
if(data=='1')
{
//alert("success");
vform.submit();
return true;
}
else
{
document.getElementById('error').innerHTML="You have entered a wrong code!";
return false;
}
});
}
else
{
document.getElementById('error').innerHTML="Code can't be empty!";
return false;
}
return false;
}
codefield function is just displaying the div on onclick event and ajax call is just checking whether the code exists in database or not..if exists returns 1 else 0.
The problem is alert message is being displayed but form is not being submitted. How can I fix this problem?
I think you are missing jquery selector.
Try to replace
vform.submit();
with
$("#vform").submit();
or you can call submit button click event like
$("#btn").click();
You are not selecting the form.
Try changing;
vform.submit();
To:
$("#vform").submit();
Please try this one, works for me.
document.getElementById("vform").submit();
Try this
document.forms["vform"].submit();
Hope this helps.
You don't have to submit form with code.
Just call validation function and control submit flow with preventDefault function.
var codevalidate = function(e) {
if (!validationCode) { // if validation code didn't pass
e.preventDefault(); // prevent form from submitting
}
}
// register callback that will be called when user submits form
document.getElementById("vform").addEventListener('onsubmit', codevalidate);
That way form will be submitted by user only if validation pass.
Also check if your data is actually returning '1' by calling console.log(data);
Form will be submitted to the current address if action is empty, is that ok?
The thing is that:
action attribute of your form element is empty. So it is being submitted but to the same page from which it is calling the .submit() method.
so you should specify action attribute first of all like:
<form id="vform" name="vform" action="vfrom_submit.php" method="post"
onsubmit="javascript:codevalidate(); return false;" >
.....
</form>
Also try changing
vform.submit();
to:
$("#vform").submit();
//OR
// document.getElementById("vform").submit();
// Although vform.submit() can also work.
Hope it helps, cheers :)!
You should use:
document.getElementById("vform").submit();
Update:
Try removing "return false;" from onsubmit attribute and remove "vform.submit();" from the if condition as well.

Hitting enter in any textbox in chrome triggers the form submit, even when there is no submit button

I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
use this syntax:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13
Try this method:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not.
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.
So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)

Categories

Resources