How to check the required fields of a form before submitting it in javascript ?
I'm working with Angularjs and as you probably know, I never reload the page.
I have created input text like this :
<input type="text" name="truck" ng-model="my model" typeahead="my typeahead" typeahead-min-length="1" required/>
Here is my submit button at the end of the form :
<button type="submit" ng-click="saveDelivery(newDelivery)" class="btn btn-primary">Create the delivery</button>
But when I submit, I go into "saveDelivery" first, and then I have the message from Google chrome : "Please fill in this field..."
How can I do to check the input before submitting ?
Look into the ng-submit directive.
This essentially looks in your defined form for any validation defined in your markup (required, type). All you have to do is take your click action and place it at the top of your form in the ng-submit directive.
<form ng-submit="saveDelivery(newDelivery)">
<input type="text" name="truck" ng-model="my model" typeahead="my typeahead" typeahead-min-length="1" required/>
<button type="submit" class="btn btn-primary">Create the delivery</button>
</form>
Because your button is defined as type 'submit', this will submit the form, preforming the 'ng-click' action for you. Angular will essentially hijack the submit, and validate your form before submitting it to 'saveDelivery'. All you have to do is define what you want validated, whether it is 'required' input, or it you do type="email" on your input, it will use HTML 5 email validation and make sure it is an email address.
Angular made it VERY easy to add validation to any form. Once validation is passed, Angular will then trigger your saveDelivery method!
Edit: 2014-02-12 - Here is a very simple example. Try clicking the submit button when the input field has nothing in it. Chrome will show validation message, enter something and the alert will run, but the form will not submit.
Example: http://plnkr.co/edit/uGT3scGJtCVJkWE0B7zp?p=preview
The browser will do the validation when the form is submitted I think (Note: not verified, this is just how I understand the flow of events. I may be wrong)
You might want to handle the form submit event to do your saveDelivery call as that (form submit) ought to happen after the validation but before the form is actually posted back. saveDelivery will finish before the form submits, and you can cancel it if needed also and do your own thing...
For example this answer to another post shows how to handle the form submit and prevent it from occuring; this might be useful if you want to call your saveDelivery method to do the actual saving but don't want the form to postback
https://stackoverflow.com/a/5384732/94099
Related
I am trying to add value to a text field in a web view using javascript. First, I add value using this code :
webView.evaluateJavaScript("document.getElementById('birds').value = 'username';", completionHandler:nil)
second I need to press Enter button to run next function. Here is text input's info:
<input type="text" name="submit" id="birds" placeholder="Write username or name and press enter" "="" class="ui-autocomplete-input" autocomplete="off">
How can I programmatically trigger enter button?
Just select the form and call submit
document.getElementById("myForm").submit();
This article could be worth a read though, you may need to select the submit button and call the onClick method instead, it depends how that particular form handles sending it's data.
I would like to know if there is a preference to using ng-click on a submit button or just having a ng-submit on a form?
My assumption is that we should use ng-submit on all forms and use ng-click on anything that isn't a form.
I know the differences that are listed below:
ng-submit allows the user to press enter when focused on a form where ng-click doesn't
ng-click can be used on any element where as ng-submit only can be applied to a form element.
I was wondering if anyone can add anything else to this list as I would like to know what the norm is in a angular project.
If we want the form not to be submitted when it is invalid, then instead of ng-click on the button, we will use ng-submit directive on the form itself
<div class="row">
<form name="adduser" ng-submit="AddUser(adduser.$valid)">
<div id="name-group" class="form-group-lg">
<input type="text"
required
name="name"
ng-model="userfullName"
class="form-control"
placeholder="Full Name">
</div>
In the ng-submit we calling a function AddUser from the controller with a parameter formname.$valid. This submit function will be only called when form is valid or in other words all the user input of the form is valid. Keep in mind that in this case from would not be submitted if form is not valid
When we use ng-click , form will be submitted even if it is invalid. Two observations for ng-click are as follows:
We were able to submit the form even if form was not valid
For the invalid inputs, the value was set to undefined in the controller
Out of experience, for mobile apps using Angular and Ionic, I used ng-click because even when the form isn't valid, the mobile keyboard arrow (Android) or GO (iOS) is enabled and will still submit it anyway. I had to use ng-click to avoid validation problems.
On web, I use ng-submit simply because, like you said, it submits on enter.
In my JSP code, I try to use ng-submit on a form.
The problem is that there are many validations for the textboxes of that form which are implemented using ng-disabled in Submit button.
Now if I click enter key on a textbox then those validations will not be implemented and the form will be submitted.
How can I add the conditions here?
The only option I could think is to move all the conditions of ng-disabled to Javascript function.
<form name="customersForm" ng-submit="findCustomers(custName, custCity)">
<button type=submit **ng-disabled="validateInputs(custName,custCity)"**
id="listButton" ng-click="findCustomers(custName,custCity)"><span>Find </span></button>
Add the novalidate attribute to your form and add the required attribute to your form elements. From there, you can play with the validation of your form with the ng- directives. The form wont be submitted until all the fields are properly filled.
I've written a form with Angular.js that requires a field to be filled out before it is submitted. The validation works correctly (the field shows a validation error when I submit the form) but the form still seems to perform its ng-click action.
Are angular forms supposed to submit despite validation errors? What's the best way to prevent it from submitting if there are validation errors?
Here's the form in question:
<form role="form">
<div class="form-group">
<label>Book Id</label><br>
<input ng-model="bookToSend.bookId" class="form-control" maxlength="40" required type="text">
</div>
<button type="submit" ng-click="sendBookUpdate(BookToSend)">Send Book Update</button>
</form>
Angular doesn't prevent forms from submitting when there are validation errors.
Actually with the snippet you pasted, the errors are shown just because by default error validation is provided with html5.
You should check the docs: https://docs.angularjs.org/guide/forms
Basically you have to name your form:
<form name="myForm" role="form">
and then you can prevent your form from submitting inside your controller with:
$scope.sendBookUpdate(BookToSend, form) {
if (form.$invalid) {
return; // and add any error to the view if you want
}
...
}
another option is to prevent submitting from the view:
<form name="myForm" role="form" ng-submit="myForm.$valid && sendBookUpdate(BookToSend)">
You could disable the button until the form has valid data
<button type="submit" data-ng-disabled="form.$invalid">Send Book Update</button>
EDIT:
When I wrote the answer below, I was under the assumption that the ngClick was completely separate from any form submission handlers that angular uses. I was wrong, however, as shown in the comments below. I'll keep this answer up, despite its inaccuracy, to inform those that come here with the same misunderstanding as I had, since, to me at least, it's kind of counter-intuitive to have an ng-click double as a submit handler.
ng-click is separate from the form's submit handler, and will run every time you click the button regardless of whether or not it passes the validation checks.
The solution to your problem would be to take sendBookUpdate(BookToSend), and place it in an ng-submit attribute on the form itself. See the code below:
<form role="form" ng-submit="sendBookUpdate(BookToSend)">
<div class="form-group">
<label>Book Id</label><br>
<input ng-model="bookToSend.bookId" class="form-control" maxlength="40" required type="text">
</div>
<button type="submit">Send Book Update</button>
</form>
Let me know if that helps.
Edit:
Here's some more info regarding ngSubmit:
https://docs.angularjs.org/api/ng/directive/ngSubmit
I have am trying to reset a textbox using the $setPristine function in AngularJS, however it doesn't seem to result in the desired behavior.
My form looks like this:
<form name="addInviteForm" ng-controller="InviteCtrl" ng-submit="sendInvitation(userEmail)">
Pristine? {{addInviteForm.$pristine}}
<!-- email input -->
<div>
<input type="email" name="email" ng-model="userEmail" placeholder="Enter email here" class="line-item-input see" required>
<span class="error" ng-show="addInviteForm.email.$error.email" style="color:red">Invalid Email</span>
</div>
<!-- submit button -->
<input type="submit" name="send" class="btn btn-success center" value="Send Invitation">
</form>
And the corresponding code in my controller:
$scope.sendInvitation = function(userEmail) {
// do some work here ...
// hmm, this doesn't seem to work ...
$scope.addInviteForm.$setPristine();
};
Though the form shows that $pristine is set to true upon form entry, then set to false when entering data in the text-box, after submitting the form it does indeed show that $pristine is set to true .... and yet the value in the textbox remains as it was before the submit button was pressed.
What am I missing here?
$setPristine does not clear values from the controls in the form:
From the docs:
Sets the form to its pristine state.
This method can be called to remove the 'ng-dirty' class and set the
form to its pristine state (ng-pristine class). This method will also
propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want
to 'reuse' a form after saving or resetting it.
As you can see from the above description, $setPristine only changes the state of the form (and thereby resets the css applied to each control in the form).
If you want to clear the values of each control, then you need to do for each in code.
This plunker shows $setPristine in action.