Sounds easy and a well known question, right? I thought so as well. How do I do this in angularJS.
CSHTML
#using (Html.BeginForm("Order", "Shop", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="container" ng-app="order" ng-controller="orderController">
<button type="submit" ng-disabled="orderButtonClicked" ng-click="orderClicked()" class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
</div>
}
AngularJS
angular.module("order", [])
.controller("orderController", ['$scope', '$http','$filter', function ($scope, $http, $filter) {
$scope.orderButtonClicked = false;
$scope.orderClicked = function () {
$scope.orderButtonClicked = true;
}
}]);
As many others reported as well, the form is not submitting when disabling or removing the button. this answer did the same, he claims it is working, but for me is a no go.
You can assume that angular is setup correctly, disabling the button works fine.
I've never had much luck with disabling the submit button in any circumstances - even if it doesn't prevent the form from submitting, the server can get confused because it expects the name/value combination from the submit button.
Instead, I generally hide the submit button, and replace it with something appropriate:
<button type="submit" ng-show="!orderButtonClicked" ng-click="orderClicked()" class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
<button ng-show="orderButtonClicked" disabled class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
Keep in mind that even in this case, the user may be able to re-submit by hitting enter in a textbox.
Try this way:
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<input type="submit" ng-disabled="orderButtonClicked" ng-click="orderClicked()">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.orderButtonClicked = false;
$scope.orderClicked = function () {
$scope.orderButtonClicked = true;
}
});
</script>
I will put a break point there and see if orderButtonClicked is set to true when orderClicked() is triggered. Just another thought, I have experience with this issue before when I have an ng-if somewhere inside the controller scope in html. This is because angular seems to create a new scope inside that ng-if dom. The best way to avoid that is to use controllerAs and then access the scope property using controllerName.propertyName.
Does the form submit if you don't disable or remove the button? The angular documentation states that, "For this reason, Angular prevents the default action (form submission to the server) unless the <form> element has an action attribute specified."
So, depending on what you're trying to accomplish, you would have to add javascript in your .orderClicked method to make an ajax call, for example, or whatever you're trying to accomplish.
Related
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.
<form name="mForm" action="${pageContext.request.contextPath}/login/insertSeller.do" method="post">
id : <input type="text" name="id" />
<input type="submit" value="register" onClick="doAction()" />
</form>
<script>
function doAction() {
var f = document.mForm;
var id = f.id;
if (id.value == "") {
alert("insert your id");
id.focus();
return false;
}
return true;
}
</script>
Is there any error to correct?
If I click the button, the alert window opens with a message,
but the data is submitted without the validation check.
What do I need to do?
Please help me :)
You really shouldn’t have inline event handlers in modern HTML. Nevertheless, you could try the following:
<input … onclick="return doAction()">
The return in the onclick causes the input to wait for permission.
For the sake of completeness, here is how I would do it in a modern browser:
First, use a button instead:
<button type="submit">register</button>
Second, give your button a name
<button name="register" type="submit">register</button>
You can give a name to the older style input element, and the process will still work.
Next, add the following to your JavaScript:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('button[name="register"]).onclick=doAction;
},false);
The main function acts as a startup script. The point of it is that it is waiting for the DOM to have loaded. Otherwise it’s not possible to look for elements that aren’t there yet.
Note that you assign to the onclick event handler the name of the function.
I have 2 buttons - Delete and Submit. Submit button is disabled initially. I am trying to enable Submit button whenever the user clicks on Disable button. I am using AngularJS 1.3.15 for this project.
main.html
<body>
<button ng-disabled="isItemDeleted" ng-init="isItemDeleted=true"
class="btn btn-lg btn-primary create-txn-button" ng-click="submit()">Submit Transaction</button>
deleteController.js
angular.module('myApp').controller('myCtrl',
function{};
$scope.deleteItem = function(item)
{
$scope.isItemDeleted = false;
var modalScope = $scope.$new(true);
modalScope.message = 'Why would you like to delete this item?';
modalScope.item = item;
modalScope.transaction = $scope.transaction;
};
But, even after setting the $scope.isItemDeleted to false, the submit button is not enabled. I believe the issue is connecting to the controller. I have to connect my div tag to the controller. But if I do it, the entire page is changed. Any clue?
Update: deleteItem() function is getting called by Delete Button.
DeleteButtonTabView.html
<div ng-controller="myCtrl">
<button ng-click="deleteItem(item)" class="btn btn-info btn-sm">Delete</button>
</div>
Please find the link to JSFiddle: https://jsfiddle.net/L1bnv9fr/
I have a multi-step form, each step having a btn-link to move to the next step. I achieve this with angular routes in this way:
<button ui-sref="next.step" class="btn btn-link"></button>
In one of the steps in the middle of the whole form I need to submit the data, so I need the already described button to submit the form as well and only if the form could be submitted then move to the next step.
I tried doing this but it is not working because it redirects to the next step without taking care about the form
<button ui-sref="next.step2" type="submit" class="btn btn-link"></button>
How can I achieve this using angular?
you don't need to use ui-sref for your next button instead use $state service from your controller as shown below
HTML Code
<form ng-submit="onFormSubmission($event)">
<button type="submit" class="btn btn-link"></button>
</form>
Controller
var successCallback = function(response) {
//process response
$state.go("next.step2");
}
$scope.onFormSubmission = function($event) {
var data = getFormData();
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
}
Use ng-submit to submit the form and show some loading message as form is getting saved, use $http to post the data and on-success take user to next route using $state.go.
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', '$state', function($scope, $state) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
$http.get('/aveData', config).then(function(response){
$state.go('next.step2')
}, function(){
alert('error saving data');
});
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
For testing, I'd like to load the page called by submit on a new tab. Is this possible?
<form target="_blank" [....]
will submit the form in a new tab... I am not sure if is this what you are looking for, please explain better...
It is also possible to use the new button attribute called formtarget that was introduced with HTML5.
<form>
<input type="submit" formtarget="_blank"/>
</form>
I have a [submit] and a [preview] button,
I want the preview to show the print view of the submitted form data, without persisting it to database. Therefore I want [preview] to open in a new tab, and submit to submit the data in the same window/tab.
<button type="submit" id="liquidacion_save" name="liquidacion[save]" onclick="$('form').attr('target', '');" >Save</button></div> <div>
<button type="submit" id="liquidacion_Previsualizar" name="liquidacion[Previsualizar]" onclick="$('form').attr('target', '_blank');">Preview</button></div>
Add target="_blank" to the <form> tag.
Since you've got this tagged jQuery, I'll assume you want something to stick in your success function?
success: function(data){
window.open('http://www.mysite.com/', '_blank');
}
Try using jQuery
<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>
Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/
This will also work great, u can do something else while a new tab handler the submit .
<form target="_blank">
Submit
</form>
<script>
$('a').click(function () {
// do something you want ...
$('form').submit();
});
</script>
Your browser options must be set to open new windows in a new tab, otherwise a new browser window is opened.