How to disable enter key in angular if condition does not match? - html

If input is null enter key should not call the function "generateCityDetailArray()" means it should be disabled, otherwise it should call the function "generateCityDetailArray()". How to achieve this?
<div class="form-group">
<input type = "text" class="col2" formControlName="pinCode"
[(ngModel)]="pinCode" required (keyup.enter)="generatecityDetailArray()" maxlength="6" />
<div *ngIf="f.pinCode.invalid && f.pinCode.touched"><strong class="text-danger" *ngIf="f.pinCode.errors?.required">Please enter the value!</strong></div>
</div>
Now, If I click enter in textbox, it is calling "generateCityDetailArray()" even when input is null. What required is if input is null and If enter is clicked then it should give a message like "Plz Enter pincode", "generateCityDetailArray()" should not be called when input is null.

why not just start method generatecityDetailArray() by
if (!this.pinCode) {
return;
}

if you have form control on input you can launch method only when input have no error
(keyup.enter)="pinCode.errors ? '' : generatecityDetailArray()"
If you want to display message to say you have to enter pincode you can use follwing syntaxe
<div *ngIf="pinCode.errors?.['required']">
Please Enter pincode.
</div>
in your class you have to define getter and setter of the form control
get pinCode() { return this.cityDetailForm.get('pinCode'); }
here the doc about validators
https://angular.io/guide/form-validation

The suggestion of starting the generatecityDetailArray() method with a check if you have a value of pinCode is a great option.
If you want to have your check performed in the template, you can also do the following:
(keyup.enter)="cityDetailForm.get('pinCode').invalid ? $event.preventDefault() : generatecityDetailArray()"
This is if you have only one validator setup for the pinCode formControl.
If you have multiple make the check cityDetailForm.get('pinCode').errors?['required'].
Also this is assuming that cityDetailForm is your formGroup. I previously thought it was simply f, because of the ngIf check on your div.
It would be best to have a getter in the component for this case, so it would be something like:
get isCityDetailInValid(): boolean {
return this.cityDetailForm.get('pinCode').errors?['required'];
// or this.cityDetailForm.get('pinCode').invalid;
}
Then your template would simply be:
(keyup.enter)="isCityDetailInValid ? $event.preventDefault() : generatecityDetailArray()"

Related

How do you add a value to datepicker from an Angular Factory?

i have an Angular Factory that gets a single date from the backend of my spring application, and i wanted to add it to an Input so the calendar input is always set with the date obtained from the backend, without the possibility for the user to change it. How could i achieve this? Should i put it on my controller or directly on the button? This is my code:
Factory(concatenated with other .factory):
.factory('DataInizioGeneraCalendario', function ($resource) {
return $resource('rest/anagrafica/dataInizioGeneraCalendario', {
get: {
method: 'GET'
}
});
Controller Function:
$scope.generaCalendario = function () {
$scope.modificaCalendarioDiv = true;
$scope.successMessage = false;
$("#idModificaCalendarioDiv").hide();
$scope.element = new Calendario();
autoScroll('generaCalendario');
$("#idErrorTemplate").hide();
$('#data').attr('disabled', false);
$("#idGeneraCalendarioDiv").show();
};
Input :
<div class="col-xs-12 col-md-2" >
<label for="dataInizio" class="row col-xs-12 control-label" style="text-align: left">da Data</label>
<input class="datepicker form-control" placeholder="gg/mm/aaaa" required type="text" id="data" ng-disabled="true" />
</div>
Edit : forgot to add, the controller function is called by the button that displays the input for the calendar.
Because your factory's GET request will return the date value asynchronously, it's better to have a $scope.date in your controller that will hold the date value that is returned from the server. Also, depending on the format in which you store dates on the backend, you might need to transform the value that is returned from the backend into the string format, so it would be properly consumed by the <input type="date"> as per Angular docs.
In your code, you need to bind the input element to this value, like this: <input ng-model="date">.
What it will do is bind this input to the data model, so that every time when user edits the input the $scope.date would be updated too.
If you do not want users to be able to edit this date, then you need to:
Keep the input field disabled <input disabled> (no need to use ng-disabled here, because you want to keep it always disabled). And also remove this line: $('#data').attr('disabled', false); in your function.
You the one-way binding, instead of two0way binding, like this: <input disabled ng-value="date">
Here is the working DEMO that shows two inputs: one that is editable and another that is not.

Spring MVC - how to bind HTML checkbox value in a boolean variable

I am very new to spring mvc world. I am trying to send boolean value to from html form checkbox. When a user check the checkbox then it will send true, false otherwise.
<form class="attendanceBook" role="form" method="post" action="/attendances">
<div class="row">
<div class="form-group">
<div class="col-xs-4">
<label class="control-label">Check Here</label>
</div>
<div class="col-xs-4">
<input type="checkbox" name="i" id="i" value="true" />
</div>
<div class="col-xs-4">
<input type="submit" value="Click"/>
</div>
</div>
</div>
</form>
After some googilng I have found this so post, where it said standard behaviour is the value is only sent if the checkbox is checked. So what I have understand that is if the checkbox checked then the form will submit with the value of checkbox, otherwise it will not submit. When there is unchecked checkbox the initialization value in data class will be effective.
But in my case every time I am submitting the form it submitting true.
here is my rest controller for the bind html form submit.
#RestController
#RequestMapping("attendances")
class AttendanceRestController {
val logger = getLogger(AttendanceRestController::class.java)
#PostMapping
fun patchAttendance(#RequestBody attendanceJson: AttendanceJson): ResponseEntity<*> {
logger.info("attendanceJson {}", attendanceJson)
return responseOK(attendanceJson)
}
}
the data class(I am using kotlin)
data class AttendanceJson (
var i: Boolean = false,
var t: String = ""
)
So what will be the method to bind boolean data from a form submission with checkbox. I am also using Thymeleaf. Thanks in advance.
I'm working in Struts and don't know much about Spring. But I faced a similar situation.
What I did was I binded the checkbox with a boolean property in my From class. So for each checkbox, one boolean variable. And at the time of submitting in front end, I'll call a JS function code is below
function verifyCheckboxes() {
document.getElementById("researchPaper").value = document.getElementById("researchPaper").checked;
document.getElementById("researchPaperSeminarProceed").value = document.getElementById("researchPaperSeminarProceed").checked;
document.getElementById("extraActivities").value = document.getElementById("extraActivities").checked;
document.getElementById("studentAchivements").value = document.getElementById("studentAchivements").checked;
}
Here you can see I'm just assigning the value of checked property of that Checkbox just before submitting. It will be either true or false.
You should remove 'value' attribute from the input. If you want the checkbox checked when loading the page, add 'checked' attribute not 'value'.
Replace the input line with this:
<input type="checkbox" name="i" id="i" checked="checked"/>
This is the reason why you always get 'true' in code behind.
It's a bit of a hack, but if you change the type of the input tag from 'checkbox' to 'text' just before the form is posted, you will receive the value, whether it is checked or unchecked.
If you use jQuery:
$("input:checkbox").each(function(){this.type='text'})

Angular 2 html form validation

I've created a form using html validations with Angular 2.
I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:
<form id="memberForm" #memberForm="ngForm" >
<input
type="text"
id="MemberName"
required
name="MemberName"
[(ngModel)]="newMember.name">
</form>
<div
[ngClass]="{'button_disabledButton' : !memberForm?.valid}"
(click)="onSubmit(memberForm?.valid, memberForm);">
<span>Next</span>
</div>
With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?
You should make getter/setter solution for your ngModel input.
In the .ts file in the appropriate class put this:
savedVar:string = '';
get variable(): string {
return this.savedVar;
}
set variable(str: string) {
this.savedVar = str;
// do your validation
}
In template use ngModel=variable like this:
<input [(ngModel)]="variable">

How do I reset a form including removing all validation errors?

I have an Angular form. The fields are validated using the ng-pattern attribute. I also have a reset button. I'm using the Ui.Utils Event Binder to handle the reset event like so:
<form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()">
<div>
<label>
Area Code
<input type="tel" name="areaCode" ng-model="areaCode" ng-pattern="/^([0-9]{3})?$/">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern">The area code must be three digits</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^([0-9]{7})?$/">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern">The phone number must be seven digits</div>
</div>
</div>
<br>
<div>
<button type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
As you can see, when the form is reset it calls the reset method on the $scope. Here's what the entire controller looks like:
angular.module('app').controller('mainController', function($scope) {
$scope.resetCount = 0;
$scope.reset = function(form) {
form.$setPristine();
form.$setUntouched();
$scope.resetCount++;
};
$scope.search = function() {
alert('Searching');
};
});
I'm calling form.$setPristine() and form.$setUntouched, following the advice from another question here on Stack Overflow. The only reason I added the counter was to prove that the code is being called (which it is).
The problem is that even after reseting the form, the validation messages don't go away. You can see the full code on Plunker. Here's a screenshot showing that the errors don't go away:
I started with the comment from #Brett and built upon it. I actually have multiple forms and each form has many fields (more than just the two shown). So I wanted a general solution.
I noticed that the Angular form object has a property for each control (input, select, textarea, etc) as well as some other Angular properties. Each of the Angular properties, though, begins with a dollar sign ($). So I ended up doing this (including the comment for the benefit of other programmers):
$scope.reset = function(form) {
// Each control (input, select, textarea, etc) gets added as a property of the form.
// The form has other built-in properties as well. However it's easy to filter those out,
// because the Angular team has chosen to prefix each one with a dollar sign.
// So, we just avoid those properties that begin with a dollar sign.
let controlNames = Object.keys(form).filter(key => key.indexOf('$') !== 0);
// Set each control back to undefined. This is the only way to clear validation messages.
// Calling `form.$setPristine()` won't do it (even though you wish it would).
for (let name of controlNames) {
let control = form[name];
control.$setViewValue(undefined);
}
form.$setPristine();
form.$setUntouched();
};
$scope.search = {areaCode: xxxx, phoneNumber: yyyy}
Structure all models in your form in one place like above, so you can clear it like this:
$scope.search = angular.copy({});
After that you can just call this for reset the validation:
$scope.search_form.$setPristine();
$scope.search_form.$setUntouched();
$scope.search_form.$rollbackViewValue();
There doesn't seem to be an easy way to reset the $errors in angular. The best way would probably be to reload the current page to start with a new form. Alternatively you have to remove all $error manually with this script:
form.$setPristine(true);
form.$setUntouched(true);
// iterate over all from properties
angular.forEach(form, function(ctrl, name) {
// ignore angular fields and functions
if (name.indexOf('$') != 0) {
// iterate over all $errors for each field
angular.forEach(ctrl.$error, function(value, name) {
// reset validity
ctrl.$setValidity(name, null);
});
}
});
$scope.resetCount++;
You can add a validation flag and show or hide errors according to its value with ng-if or ng-show in your HTML. The form has a $valid flag you can send to your controller.
ng-if will remove or recreate the element to the DOM, while ng-show will add it but won't show it (depending on the flag value).
EDIT: As pointed by Michael, if form is disabled, the way I pointed won't work because the form is never submitted. Updated the code accordingly.
HTML
<form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()">
<div>
<label>
Area Code
<input type="tel" name="areaCode" ng-model="areaCode" ng-pattern="/^([0-9]{3})?$/">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern" ng-if="searchForm.areaCode.$dirty">The area code must be three digits</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^([0-9]{7})?$/">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern" ng-if="searchForm.phoneNumber.$dirty">The phone number must be seven digits</div>
</div>
</div>
<br>
<div>
<button type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
JS
$scope.search = function() {
alert('Searching');
};
$scope.reset = function(form) {
form.$setPristine();
form.$setUntouched();
$scope.resetCount++;
};
Codepen with working solution: http://codepen.io/anon/pen/zGPZoB
It looks like I got to do the right behavior at reset. Unfortunately, using the standard reset failed. I also do not include the library ui-event. So my code is a little different from yours, but it does what you need.
<form name="searchForm" id="searchForm" ng-submit="search()">
pristine = {{searchForm.$pristine}} valid ={{searchForm.$valid}}
<div>
<label>
Area Code
<input type="tel" required name="areaCode" ng-model="obj.areaCode" ng-pattern="/^([0-9]{3})?$/" ng-model-options="{ allowInvalid: true }">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern">The area code must be three digits</div>
<div class="error" ng-message="required">The area code is required</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" required name="phoneNumber" ng-model="obj.phoneNumber" ng-pattern="/^([0-9]{7})?$/" ng-model-options="{ allowInvalid: true }">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern">The phone number must be seven digits</div>
<div class="error" ng-message="required">The phone number is required</div>
</div>
</div>
<br>
<div>
<button ng-click="reset(searchForm)" type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
And JS:
$scope.resetCount = 0;
$scope.obj = {};
$scope.reset = function(form_) {
$scope.resetCount++;
$scope.obj = {};
form_.$setPristine();
form_.$setUntouched();
console.log($scope.resetCount);
};
$scope.search = function() {
alert('Searching');
};
Live example on jsfiddle.
Note the directive ng-model-options="{allowinvalid: true}". Use it necessarily, or until the entry field will not be valid, the model value is not recorded. Therefore, the reset will not operate.
P.S. Put value (areaCode, phoneNumber) on the object simplifies purification.
Following worked for me
let form = this.$scope.myForm;
let controlNames = Object.keys(form).filter(key => key.indexOf('$') !== 0);
for (let name of controlNames) {
let control = form [name];
control.$error = {};
}
In Short: to get rid of ng-messages errors you need to clear out the $error object for each form item.
further to #battmanz 's answer, but without using any ES6 syntax to support older browsers.
$scope.resetForm = function (form) {
try {
var controlNames = Object.keys(form).filter(function (key) { return key.indexOf('$') !== 0 });
console.log(controlNames);
for (var x = 0; x < controlNames.length; x++) {
form[controlNames[x]].$setViewValue(undefined);
}
form.$setPristine();
form.$setUntouched();
} catch (e) {
console.log('Error in Reset');
console.log(e);
}
};
I had the same problem and tried to do battmanz solution (accepted answer).
I'm pretty sure his answer is really good, but however for me it wasn't working.
I am using ng-model to bind data, and angular material library for the inputs and ng-message directives for error message , so maybe what I will say will be useful only for people using the same configuration.
I took a lot of look at the formController object in javascript, in fact there is a lot of $ angular function as battmanz noted, and there is in addition, your fields names, which are object with some functions in its fields.
So what is clearing your form ?
Usually I see a form as a json object, and all the fields are binded to a key of this json object.
//lets call here this json vm.form
vm.form = {};
//you should have something as ng-model = "vm.form.name" in your view
So at first to clear the form I just did callback of submiting form :
vm.form = {};
And as explained in this question, ng-messages won't disappear with that, that's really bad.
When I used battmanz solution as he wrote it, the messages didn't appear anymore, but the fields were not empty anymore after submiting, even if I wrote
vm.form = {};
And I found out it was normal, because using his solution actually remove the model binding from the form, because it sets all the fields to undefined.
So the text was still in the view because somehow there wan't any binding anymore and it decided to stay in the HTML.
So what did I do ?
Actually I just clear the field (setting the binding to {}), and used just
form.$setPristine();
form.$setUntouched();
Actually it seems logical, since the binding is still here, the values in the form are now empty, and angular ng-messages directive is triggering only if the form is not untouched, so I think it's normal after all.
Final (very simple) code is that :
function reset(form) {
form.$setPristine();
form.$setUntouched();
};
A big problem I encountered with that :
Only once, the callback seems to have fucked up somewhere, and somehow the fields weren't empty (it was like I didn't click on the submit button).
When I clicked again, the date sent was empty. That even more weird because my submit button is supposed to be disabled when a required field is not filled with the good pattern, and empty is certainly not a good one.
I don't know if my way of doing is the best or even correct, if you have any critic/suggestion or any though about the problem I encountered, please let me know, I always love to step up in angularJS.
Hope this will help someone and sorry for the bad english.
You can pass your loginForm object into the function ng-click="userCtrl.login(loginForm)
and in the function call
this.login = function (loginForm){
loginForm.$setPristine();
loginForm.$setUntouched();
}
So none of the answers were completely working for me. Esp, clearing the view value, so I combined all the answers clearing view value, clearing errors and clearing the selection with j query(provided the fields are input and name same as model name)
var modelNames = Object.keys($scope.form).filter(key => key.indexOf('$') !== 0);
modelNames.forEach(function(name){
var model = $scope.form[name];
model.$setViewValue(undefined);
jq('input[name='+name+']').val('');
angular.forEach(model.$error, function(value, name) {
// reset validity
model.$setValidity(name, null);
});
});
$scope.form.$setPristine();
$scope.form.$setUntouched();

Show element if observable value is null

Is it possible to use the Knockout's visible: or if: data bindings to check to see if an observable's value is (explicitly) null?
I've got two radio buttons, and if either one is checked, it sets an observable's value to either "True" or "False". Otherwise the observable's value is null. I'd like an element to conditionally display if the observable value is null. The following doesn't seem to work:
<div data-bind="visible: specificObservable === null"> Example </div>
<!-- shows the element when null, but not false, nor 'False' -->
Guessing that specificObservable is an observable, try:
<div data-bind="visible: specificObservable() === null"> Example </div>
You need to call the observable to get the actual value it contains. specificObservable is a function and therefore not null, even if the value it contains is null.
This is something that can trip you up in knockout because knockout will automatically unwrap observables if they are used by themselves. So if you did:
<div data-bind="visible: specificObservable"> Example </div>
And it will call specificObservable for you and be visible if specificObservable() is truthy. But once you start using it in a longer statement you need to explicitly unwrap it yourself.
Don't forget the closing double quote " after the call to function specificObservable()