AngularJS - ngClick is blocking submit key action - javascript

The user of my web should enter a simple code using buttons in my form and after that he should click Ok or hit enter and continue with proccess.
The thing is that the enter key is not submiting my form, is executing other method that is called from ng-click. How can avoid enter key call the ng-click method?
myapp.js
var myApp = angular.module('myApp',[]);
myApp.controller('myformcontroller', ['$scope', function ($scope){
// Procesing data from form.
$scope.signin = function () {
}
}]);
myApp.controller('mycontroller', ['$scope', function ($scope){
$scope.do = function() {
alert('ng-click pressed!');
}
}]);
myform.html
<div ng-controller="myformcontroller">
<form name="myForm"
role="form"
ng-submit="signin()"
novalidate>
<input type="text"/>
<div ng-controller="mycontroller">
<a href="javascript:void(0);" ng-click="do()">
clickme!
</a>
</div>
<button type="submit">Ok</button>
</form>
</div>
Press click me and hit enter key after on My Fiddle

You can ommit html rules with jquery.
Add id to a form and button first:
<form id="mydiv" name="myForm"
role="form"
ng-submit="signin()"
novalidate>
<div ng-controller="mycontroller">
<a href="javascript:void(0);" ng-click="do()">
<img src="img/a-letter.png" alt="">
</a>
</div>
<button id="mydiv2" type="submit">Ok</button>
</form>
And then set listener on enter up:
$("#mydiv").keyup(function(event){
if(event.keyCode == 13){
$("#mydiv2").click();
}
});
So it's not elegant, but you can submit form with simulating click on enter pressed.

It is not blocking. You're missing a standard input to bubble the properly handled click event. If there is no input, the form is not submitted by default. It's not an angular issue. Take a look here https://stackoverflow.com/a/477699/4573999
EDIT
More detailed explanation based on comments. The question is not about the submit element. Sure, you have a button type submit. The for other elements inside the form there is a default behavior. And for input element the default on enter key is to submit the form that it is surrounded by. But for the anchor tag it is not. Because it is not supposed to provide any data. Why would you want to submit a form on a link? So in your case you should submit the form programmatically by calling appropriate method.
myApp.controller('myformcontroller', ['$scope', function ($scope){
$scope.signin = function () {
alert('submit!');
}
}]);
myApp.controller('mycontroller', ['$scope', function ($scope){
$scope.do = function() {
alert('ng-click pressed!');
$scope.signin();
}
}]);
Check updated fiddle
If you'd like to get this in a generic way, you can parse the ng-submit value like here How to programmatically submit a form with AngularJS

Related

Why is my button function not being called? [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.

Contact form with AJAX call still redirecting after submit [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.

ng-click instead of submit

After I click submit in a form, some javascript runs to modify the data and sends it to whatever the form action is specified in the HTML:
// Submit the form:
// $form.get(0).submit();
$('.submit', $(event.target.form)).click();
I would like to instead use ng-click and send that info to an angular function, such as vm.checkout().
How can I make this happen?
Use ngSubmit directive instead of ngClick for form submit.It binds to the submit event which is fired when a form is submitted.
ng-submit works only when forms submitted.
where as ng-click can work without form submit event.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.submitMe = function () {
alert('Submitted');
};
});
<div ng-app="myApp" ng-controller="MyCtrl">
<form ng-submit="submitMe()" name="myForm">
<button type="submit">submit</button>
</form>
</div>
JavaScript
$scope.submit = function(data){
// do something with data
}
HTML
<form>
<input type="text" ng-model="temp.name" name="name"/>
<button type="button" ng-click="submit(temp)">Submit</button>
</form>
If it is a form you are submitting you should use ng-submit. Add the ng-submit tag with the corresponding function which will be in your controller. Then, you will be able to handle the data from your form submission.
For example:
<form ng-submit="submit()" ng-controller="ExampleController"></form>

AngularJS : Show and hide class on ng-click

I am working on a website in AngularJS. I have a form which is set to "display:none" on purpose.
I have a button which says create. What i want is that when i click on the create button the form set to "display:none" should change to "display:block" and the create button should hide.
Also after submitting the form , the form should hide and the create button should be visible again.
P.S: Now i understand that there are a couple of ways to do this, like i could use the ng-show or ng-hide directive. OR i could use ng-click directive. I want to know what is the best programming practice in this case when developing a serious and professional web application.
Its a simple thing so if you could please provide the code that would be great.
Simply use the ngClick directive with the ngShow directive see below for a working example:
var myApp = angular.module('myApp', []);
myApp.controller('FormController', ['$scope',
function($scope) {
// init showForm to false;
$scope.showForm = false;
// init empty user object for our form
$scope.user = {};
$scope.submitForm = function() {
// logic when the form is submitted
//...
// reset the user
$scope.user = {};
// finally hide the form
$scope.showForm = false;
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="FormController">
<button ng-hide="showForm" ng-click="showForm = true">Show form</button>
<form ng-show="showForm" ng-submit="submitForm()">
<input type="text" name="firstname" ng-model="user.firstname" />
<input type="submit" value="submit" />
</form>
</div>
</div>
We are setting the form to show if showForm is true.
This variable is toggled using the ngClick directive on the button element and is also explicitly set to false in the controller within the submitForm function.
We use the ngSubmit directive to bind submitForm() to the onsubmit event. When the form is submitted, you run your logic and then the form is reset and hidden.
I'd use ng-click along with ng-show.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="hideShow" ng-show="showToggle">
<form ng-submit="showToggle = false"></form>
fghfgh
</div>
<button ng-hide="showToggle" ng-click="showToggle = !showToggle">Click To Show</button>
</div>
That will start hidden, and show when you click the button.
Initially show Click To Show button and when click on this button then will show your content and show another button Click To hide button so also need to use ng-show for both buttons.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="hideShow" ng-show="isShow">
<p>here your form or other content
<p>
</div>
<button ng-click="isShow= !isShow" ng-show="!isShow">Click To Show</button>
<button ng-click="isShow= !isShow" ng-show="isShow">Click To hide</button>
</div>

Clicking a button within a form causes page refresh

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.

Categories