Consider a form with three buttons:
<form ng-submit="updateUser()"> <div>Name <input type="text" ng-model="userToEdit.name" /></div> <div> <button class="btn btn-primary" ng-click="updateUser()">Save</button> <button class="btn" ng-click="cancelEdit()">Cancel</button> <button class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button> </div> </form>
When I click cancel, cancelEdit() is being called, then updateUser() is being called. I don't want the updateUser() method to be called. Is there a way to suppress this form submission (preferebly wtihout jQuery?)
Note: I'd still like to be able to hit enter and default to the Save action.
There is a type
attribute for the <button>
which defaults to submit - see this spec. Thus every button in your form is a submit button. You need to specify the button type for buttons which should not trigger the form submission, like this:
<form ng-submit="updateUser()"> <div>Name <input type="text" ng-model="userToEdit.name" /></div> <div> <button class="btn btn-primary">Save</button> <button type="button" class="btn" ng-click="cancelEdit()">Cancel</button> <button type="button" class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button> </div> </form>
And also no need to put the submit action to both ng-click
and ng-submit
- it will trigger double submit. I would advise to use ng-submit
because it catches all ways of form submission, like pressing ENTER and not only clicking on submit button.
Hope this helps :)
Try this
<form ng-submit="updateUser()"> <div>Name <input type="text" ng-model="userToEdit.name" /></div> <div> <button class="btn btn-primary">Save</button> <a class="btn" ng-click="cancelEdit()">Cancel</a> <a class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</a> </div> </form>
or this
<form> <div>Name <input type="text" ng-model="userToEdit.name" /></div> <div> <button class="btn btn-primary" ng-click="updateUser()">Save</button> <button class="btn" ng-click="cancelEdit()">Cancel</button> <button class="btn btn-danger" ng-click="deleteUser(userToEdit)"><i class="icon-trash"></i> Delete</button> </div> </form>
ultimately I don't think you need updateUser()
twice in the html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With