Angular binding with form automatically - html

jsfiddle demo: https://jsfiddle.net/zpufky7u/1/
I have many forms on the site, which was working fine, but just suddenly angular is binding all the forms with class="ng-pristine ng-valid"
Is this a setting or what can cause angular to auto-bind forms?
I'm using angular version: angular#1.4.7
Following is my form, as you can see there is no model inside form
<form name="app_bundle_notification_type" method="post">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<div class="checkbox">
<label class="required">
<input type="checkbox" id="app_bundle_notification_type_isNewsletter" name="app_bundle_notification_type[isNewsletter]" required="required" value="1" checked="checked">
Yes, I would like to receive email newsletter for new deals, coupons and news.
</label>
</div>
</div>
</div>
</div>
<div class="row m-y-1">
<div class="col-sm-12">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
<input type="hidden" id="app_bundle_notification_type__token" name="app_bundle_notification_type[_token]" class="form-control" value="b-_qAF6LHFy_GtPlsFG3iguhVXfGsj38TXm22Ke8j0k">
</form>
Angular app.js
define(['angular'], function() {
var app = angular.module("myApp", []);
app.init = function () {
angular.bootstrap(document, [app.name]);
};
return app;
});
So far I found the issue, if you do angular.bootstrap(document, [app.name]); then it is binding the form. it was not causing this issue before.

Presuming you are using a form tag around your form, Angular automatically adds those classes to each ng-model inside your form.
This allows you much more control over the elements inside your form to perform any validation or logic you want your form to capture or enforce before submitting.
Much of it is listed in the docs here

https://docs.angularjs.org/api/ng/directive/form
For this reason, Angular prevents the default action (form submission
to the server) unless the <form> element has an action attribute
specified.
New version accepts empty action="", check release version at https://github.com/angular/angular.js/pull/3776

Related

Can't submit the page even though using preventDefault in laravel

I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action) My form inputs are filled dynamically here is my code.
HTML
<div class="modal-body">
<form id="update_form">
<!-- loaded below -->
</form>
</div>
another request that fill my form data
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<input type="hidden" name="request_type" value="{{RegisterTypesNames::Faculty}}">
<label>University</label>
<select name="university" class="custom-select" id="university{{$action}}">
<option selected value="1">University of Cansas</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Faculty</label>
<input type="text" class="form-control" name="faculty" id="faculties{{$action}}">
</div>
<div class="form-group col-md-6">
<label>Init</label>
<input type="text" class="form-control" name="short_name" id="short_names{{$action}}">
</div>
</div>
<button type="submit" class="btn btn-primary"><span class="fa fa-save"></span> Save</button>
And jquery code
$('#update_form').submit(function (e) {
$.ajax({
url: '/update_data',
type: "POST",
data: $('#update_form').serialize(),
dataType: "json",
success: function (data) {
console.log(data.result);
}
});
e.preventDefault();
});
Note: I use multiple partial forms like this all others works fine
I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action)
Interpretation: the statements "page refreshed" and "used preventDefault" indicate that the problem is that the code inside the $("#id").submit( is not firing and the page's default submit is kicking in hence the "page refreshed".
As the jquery event is not firing, it likely means that the HTML does not exist when the script runs. This can usually be handled by putting in a doc.ready; OP indicates that it's already in doc.ready.
The alternative is to use event delegation. Though it's not clear if the code is running before the HTML is generated or if the HTML is added after (subtle difference).
The solution for event delegation is to use:
$(document).on("submit", "#update_form", function(e) {
e.preventDefault();
$.ajax({...
});

Angular 7 template form - form.reset() not working

I am trying to reset my form input value and it's not resetting the value nor the ngmodel control state.
here is my HTML:
TrackPage.html:
<form #trackForm="ngForm">
<div class="form__field" style="padding-top: 10px; ">
<search-input [(inputModel)]="trackingNumber" [label]="'tracking.tracking-placeholder' | translate">
</search-input>
</div>
<div>
<button id="trackBtn" type="button" class="track-button" [style.backgroundColor]="brand.style.mainColor"
(click)="searchTracking(); trackForm.reset()"
[style.color]="brand.style.fontColor">{{ 'tracking.tracking-btn' | translate | uppercase}}
</button>
</div>
</form>
Input Component:
<input id="trackingNumber" [(ngModel)]="inputModel" [ngClass]="{ 'form__field--has-value': inputModel }" type="text"
(ngModelChange)="changeData()" [required]="true" [style.font-family]="fontFamily" #spy />
<label for="trackingNumber" [style.font-family]="fontFamily">{{label}}</label>
Input Component.ts:
changeData() {
this.inputModelChange.emit(this.inputModel);
console.log(this.inputModel);
}
Here trackForm.reset() is not working. The only difference I see from Angular IO documentation is I use separate input component.
Not sure why it's not working.Any help?
It looks like the HTML element you want to reset is not inside the form you're calling.
Try to move it outside of the component and put it inside form or just refresh the model you're giving as an input when you want to refresh the form.
Hope it helps!

Unable to get ng-message to disappear when form is valid or reference form in controller

I know this question has been asked many times but none of the answers/resources have been able to help me.
I am trying to make a simple form in angular that will take a number and display a message if it is negative:
<div layout-padding ng-controller="BaseController as vm">
<form name="vm.mechanicalForm">
<input type="number" min="0" name="test" ng-model="vm.building.numberOfChillers" required />
<div ng-messages="vm.mechanicalForm.number.$error">
<div ng-message="min">
Test worked
</div>
</div>
<input type="button" ng-click="vm.save()" value="Save" />
</form>
Additionally, when I save the form, I want the controller to log one message if the form is valid, and another if it is not valid:
var app = angular.module('plunker', ['ngMessages']);
export class BaseController {
public mechanicalForm;
public building;
constructor() {
this.mechanicalForm = {};
this.building = {
'numberOfChillers': 0
};
}
public save() {
if (this.mechanicalForm.$valid) {
console.log("This worked");
}
else {
console.log("This did not work");
}
}
}
app.controller('BaseController', BaseController);
But it seems like my controller is not able to see the form at all. According to everything I have read I seem to be writing the code correctly. My two questions are:
1: Why will the ng-message not disappear when my input is valid?
2: Why is my controller not able to see my form object?
Here is a code pen Demonstrating my issue. I am using AngularJS 1.5.3
For reference, here are the resources I have referred to so far:
How to use ng-messages
AngularJS form and control state
Using 'controller as' syntax
common issues with ng-messages
<div layout-padding ng-controller="BaseController as vm">
<form name="vm.mechanicalForm">
<input type="number" min="0" name="test" ng-model="vm.building.numberOfChillers" required />
̶<̶d̶i̶v̶ ̶n̶g̶-̶m̶e̶s̶s̶a̶g̶e̶s̶=̶"̶v̶m̶.̶m̶e̶c̶h̶a̶n̶i̶c̶a̶l̶F̶o̶r̶m̶.̶n̶u̶m̶b̶e̶r̶.̶$̶e̶r̶r̶o̶r̶"̶>̶
<div ng-messages="vm.mechanicalForm.test.$error">
<div ng-message="min">
Test worked
</div>
</div>
<input type="button" ng-click="vm.save()" value="Save" />
</form>
The DEMO on PLNKR

Can't make the validation work in Bootstrap

I'm trying to implement validation by Bootstrap and I've pasted the following sample on my page:
<div class="form-group has-success">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control form-control-success" id="inputSuccess1">
<div class="form-control-feedback">Success! You've done it.</div>
<small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>
I can see that the appearance of the input control has changed (it's a bit rounded and much more aesthetic now) but it still doesn't show the green border as can be seen on the page linked to. The Bootstrap I'm linking to is pointed out as follows.
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
I have tried to google for this issue but to no avail. I have a fiddle illustrating the issue.
What can I do about it? What am I missing?
Bootstrap 5 (Update 2021)
Since jQuery is no longer required for Bootstrap 5, it's easy to do client-side validation with vanilla JavaScript. The docs include a generic code example that should work on all forms with needs-validation..
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
Bootstrap 5 Form Validation Demo
Bootstrap 4 (Original Answer)
Validation has changed as of the Bootstrap 4 beta release.
The valid state selectors use the was-validated class which would be added dynamically after validating the form via client-side JavaScript. For example...
<form class="container was-validated" novalidate="">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control" name="i1" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
<div class="form-group">
<label class="form-control-label" for="inputSuccess2">Input with danger</label>
<input type="text" class="form-control" name="i2" required="" id="inputSuccess2">
<div class="invalid-feedback">That didn't work.</div>
</div>
<div class="">
<button type="submit" class="btn btn-secondary">Text</button>
</div>
</form>
https://codeply.com/go/45rU7UOhFo
Form Validation Example Demo - Bootstrap 4.0.0
As explained in the docs, if you intend to use server-side validation you can simply set the is-valid or is-invalid classes on the form-controls...
<form class="container">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control is-valid" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
</form>
It appears the validation changes again in the final release version of Bootstrap 4: http://getbootstrap.com/docs/4.0/components/forms/#validation.
It becomes more complicated than I thought.
Custom style client side validation is recommended:
When validated, the form adds a class named was-validated.
Feedback messages are wrapped within .valid-feedback or .invalid-feedback.
For server-side validation:
No need for was-validated class on the <form> tag.
Add .is-valid or .is-invalid on the input control.
Add .invalid-feedback or .valid-feedback for the feedback message.
my simple way....
<input type="text" class="form-control" id="unombre"
placeholder="su nombre" name="vnombre" required
onblur="valida(this.id)">
<script>
function valida(v) {
var dato = document.getElementById(v).value
document.getElementById(v).className +=' is-valid';
}
</script>

AngularJs: Why we always keep form submit button disabled?

I have worked on AngularJs and now working on Angular2. Whenever I searched for form validation in angular I always found the submit button like below:
In AnglarJs
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
In Angular2
<button type="submit" class="btn btn-default"
[disabled]="!heroForm.form.valid">Submit</button>
But I wanted the submit button should be enable and whenver user click on that we prompt the error below the text fields. There is no exact solution mentioned for this purpose.
I found some of that some of the users directly clicks on submit button and they wanted to fill only required fileds.
This is my observation only may be some of you also experienced the same while development.
For AngularJs 1 I am using custom-submit directive from here
https://gist.github.com/maikeldaloo/5133963
So please suggest me any solution to provide custom-submit in angular2 also.
---- Sample Login Form (Angular2) ---
<form class="ui large form" (ngSubmit)="onUserLogin(loginForm.form.valid)" #loginForm="ngForm" method="post" novalidate>
<sm-loader [complete]="!formSubmited" class="inverted" text="Loading..."></sm-loader>
<div class="field">
<input type="email" name="email" placeholder="Email" [(ngModel)]="login.email" #email="ngModel" required />
<div [hidden]="email.valid || email.pristine" class="error text-left">
Email is required
</div>
</div>
<div class="field">
<input type="password" name="password" placeholder="Password" [(ngModel)]="login.password" #password="ngModel" required />
<div [hidden]="password.valid || password.pristine" class="error text-left">
Password is required
</div>
</div>
<button class="fluid yellow large ui button" type="submit">Login</button>
</form>
Please check what custom-submit directive are doing. Please give me answers the based on that. I know I can check the form valid status on controller level, but why this way I can say only form is not valid, I can not say which field is empty (we can also check this which field is valid, but don't know how to enable the error divs from controllers)
Please refer this...
https://gist.github.com/maikeldaloo/5133963
Thanks,
Just set a state and show/hide the errors depending on the state:
onSubmit() {
if(hasErrors()) {
this.hasErrors = true;
return false; // preventDefault
}
this.postData(); // process submit event
}
<div *ngIf="hasError">
... error info here
</div>
This way we actually validate whether you have entered the correct values or not. If any of the value fails then submit button gets disabled otherwise enabled.
For ex: E-mail : If email id doesn't have # and ., then it will be considered as dirty, which wouldn't lead to enable the submit button.
Edited:
To display the message you can do one thing:
<input type="submit" ng-click="done(heroForm.form.valid)" />
And in controller you can do this way.
$scope.done = function(valid){
if(valid) {
// Form content is valid, process it
} else {
// show error and do nothing.
}
}