Run validation on input based on change of checkbox in Angular 4 - javascript

I am looping through an array of key values to create a list of checkboxes each with a sibling disabled input. On check of each checkbox, the sibling input text field becomes enabled and is required. In this view there is a 'previous' and 'next' button and the 'next' button should be disabled if a user selects a checkbox and then does not enter anything in it's required sibling input. I almost have this working, however the 'next' button should become disabled as soon as a user checks the box as this would mean they have not entered anything in the required text input. Right now the 'next' button only becomes disabled if a user checks the checkbox, focuses on the sibling input and then leaves without entering.
My HTML...
<div *ngFor="let promotion of promotionOptions; let i = index">
<div class="col-md-6 input-container radio-label">
<mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key">
{{ promotion.name }}
</mat-checkbox>
</div>
<mat-input-container>
<input matInput [disabled]="promotion.key" placeholder="Cost" name="promotionCost{{i}}" #promotionCost="ngModel" [ngModel]="" (keyup)="promotionCostInput($event.target.value)"
[required]="!promotion.key" type="number">
<div *ngIf="promotionCost.errors && (promotionCost.dirty || promotionCost.touched)" class="alert alert-danger cost-alert">
<div [hidden]="!promotionCost.errors.required">Please enter the checked promotion's cost</div>
</div>
</mat-input-container>
</div>
<div class="clearfix"></div>
<div class="button-container">
<button class="main-btn dark icon-left" (click)="updateStep(1)"><i class="fa fa-angle-left"></i>Previous</button>
<button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next<i class="fa fa-angle-right"></i></button>
</div>
And the method I'm using in my .ts file for disabling the 'next' button:
promotionCostInput(value) {
if (!value) {
this.promotionCostValid = false;
} else {
this.promotionCostValid = true;
}
}
How can I validate the sibling input when a user checks the checkbox?

Your problem is that the state of your next button is only updated when the keyup event is fired on any of your inputs. Besides, it is updated with only the value of one input but according to what you say, youwant to check that every inputs of your ngFor is filled.
I suggest you to store the value of your inputs in your model and to check that promotion cost is valid for all promotions any time the input change or a checkbox is checked.
<div *ngFor="let promotion of promotionOptions; let i = index">
<div class="col-md-6 input-container radio-label">
<mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key; checkPromotionCost();">
{{ promotion.name }}
</mat-checkbox>
</div>
<mat-input-container>
<input
matInput
[disabled]="promotion.key"
placeholder="Cost"
name="promotionCost{{i}}"
(keyup)="promotion.cost = $event.target.value; checkPromotionCost();"
[required]="!promotion.key" type="number"
>
<div *ngIf="promotionCost.errors && (promotionCost.dirty || promotionCost.touched)" class="alert alert-danger cost-alert">
<div [hidden]="!promotionCost.errors.required">
Please enter the checked promotion's cost</div>
</div>
</mat-input-container>
</div>
<div class="clearfix"></div>
<div class="button-container">
<button class="main-btn dark icon-left" (click)="updateStep(1)"><i class="fa fa-angle-left"></i>Previous</button>
<button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next<i class="fa fa-angle-right"></i></button>
</div>
And in the controller:
checkPromotionCost() {
this.promotionCostValid = true;
this.promotionOptions.forEach(promotion => {
if (promotion.key && promotion.cost === '') {
this.promotionCostValid = false;
}
});
}

Related

Javascript hide/show elements does not work properly

I have added this checkbox to my form:
<div class="row">
<div class="form-group col">
<input type="checkbox" name="prd_presell" id="product_presell"
onclick="presellTXT()" value="TRUE" #if(!empty($product)) #if($product->prd_presell == 'TRUE') checked #endif #endif>
<label for="presell_product">Presell Product</label>
</div>
</div>
So there is an onClick function named presellTXT() which goes like this:
function presellTXT() {
var presell_checkbox = document.getElementById("product_presell"); // get checkbox
var presell_text = document.getElementById("show_presell_text"); // text div
var presell_text_input = document.getElementById("presell_product_text"); // text input
if (presell_checkbox.checked == true){
presell_text.style.display = "block";
} else {
presell_text_input.value = "";
presell_checkbox.value = "";
presell_text.style.display = "none";
}
}
So when the checkbox is checked, it basically shows the element with an id of show_presell_text:
<div class="row" id="show_presell_text">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
So when the page loads, it should not be showing the Product Presell Text unless the checkbox is checked.
Now if you take a look at jsfillde example, you can see as soon as the page loads, the text input appears however the checkbox is not checked at all!
So how to hide the text input when the page loads and the checkbox is not checked?
Note: I don't want to use CSS for this because I need to determine correctly if prd_presell is checked on page loads (because of #if($product->prd_presell == 'TRUE') which retrieves data from the DB) then it has to show the Product Presell Text text input.
UPDATE:
I tried adding this:
#show-presell-text.hidden {
display: none !important;
}
And adding this to the div:
<div class="row" id="show_presell_text" class="#if(!empty($product)) #if($product->prd_presell != 'TRUE') hidden #endif #endif">
But does not work and hide the element.
to hide/show the elements on load then this can be easily done by adding an if statement like so
#if (!empty($product))
<div class="row" id="show_presell_text">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
#endif
This will completely omit the element you want at page load if empty and you can add it via JS code. However, If you want to just hide it using CSS classes you can do this:
<div class="row" id="show_presell_text" class="#if (empty($product)) hidden #endif">
<div class="col-lg-12">
<div class="form-group">
<label>Product Presell Text:</label>
<input name="prd_presell_text" id="presell_product_text" class="form-control" value="{{ old('prd_presell_text', !empty($product) ? $product->prd_presell_text : '') }}">
</div>
</div>
</div>
If the product is empty the class will not be present and you can use CSS to set the element to display: none if the class is absent. Let me know if I can clarify further or if I got something wrong.
Edit: A better alternative for the second code block would be to add a hidden class as suggested below if the product is empty and then use it to hide it via CSS. You can then simply add or remove this class via JS as needed.
#show-presell-text.hidden {
display: none;
}
You can try out something like this.
<div class="row" id="show_presell_text" style="display: none">
By default set the display as none and based on the condition in function set it as block/ none.

How can I get a input required with vuejs

I have my chat and I dont want people to send empty message so I would like that my input become required. Thanks for your help.
I tried to put "required='required'" in the input line, I also tried veeValidate but it broke my chat when I use it, I also tried to put "Required = true" in Props and data but without a good result
This is ChatForm.vue
<template>
<div class="input-group" >
<input id="btn-input" type="text" name="message" class="form-control input-sm" placeholder="Ecrire..." v-model="newMessage" #keyup.enter="sendMessage">
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="btn-chat" #click="sendMessage">
&#10003
</button>
</span>
</div>
</template>
<script>
export default {
props: ['user'],
data() {
return {
newMessage: '',
}
},
methods: {
sendMessage() {
this.$emit('messagesent', {
user: this.user,
message: this.newMessage
});
setTimeout(function() {
const messages = document.getElementById('mess_cont');
messages.scrollTop = messages.scrollHeight;
}, 200);
this.newMessage = '';
}
}
}
</script>
And this is my form in the app.blade.php
<div id="app" class="container-chat">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<div class="col-md-12 col-md-offset-2">
<div class="panel-body panel-content" id="mess_cont">
<chat-messages id="mess" :messages="messages" :currentuserid="{{Auth::user()->id}}"></chat-messages>
</div>
<div class="panel-footer">
<chat-form
v-on:messagesent="addMessage"
:user="{{ Auth::user() }}"
></chat-form>
</div>
</div>
</div>
</div>
</div>
Try to change your ChatForm.vue like this:
<template>
<form #submit.prevent="sendMessage">
<div class="input-group" >
<input id="btn-input" type="text" name="message" class="form-control input-sm" placeholder="Ecrire..." v-model="newMessage" required>
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" type="submit" id="btn-chat">
&#10003
</button>
</span>
</div>
</template>
You are not treating the input in the correct way, the input which is required needs to be inside a form and the required keyword will prevent the form submission if the input field is empty.
There are a few things I would do differently.
1/ Wrap your chat form in a tag, and execute the sendMessage() method on submit. This will give your users a nicer experience, as they can just to submit the message.
2/ Convert the button into a submit button so it triggers the form.submit event.
3/ You can easily disable the button by checking whether newMessage has contents. I don't think you need vee validate or anything else to achieve this; for something as simple as a chat form, your user doesn't need much more feedback than seeing a disabled button to realise (s)he needs to write something first.
4/ in the addMessage method you can just check the contents of newMessage and not do anything when it's empty. This is perfectly fine because you already hinted the user by disabling the button too.
I think this is a subtle way where you guide your user, but don't overdo it.
Please add name attributes to all of your form elements. Some of the element in my form had name attribute and some didn't. Element which had name attributes worked correctly but the one's which didn't had name failed.

Angular2 FormArray insert does not update view accordingly

So I have a FormArray containing FormGroups with 3 controls.
Visually it looks like a table with 3 inputs on each row. Here is how it looks:
I want when the user presses tab or enter at the last input in the row - a new empty row to be added after it. So I added (keydown)="addRow($event.keyCode, i)" to the last input and created the function:
public addRow(keyCode, index)
{
if (keyCode !== 9 && keyCode !== 13) {
return;
}
let formItems = this.form.get('items') as FormArray;
formItems.insert(
index + 1,
this.formBuilder.group({
'start': ['', Validators.required],
'title': ['', Validators.required],
'category': [''],
})
);
}
Afther the FormGroup is pushed, I can see the controls correctly in the form array, however the view is updated strangely. After for example I press tab on the last input in the first row I get this result:
Last row is removed and I get two empty rows in the after the first. I couldn't find out why. Here is the FormArray after the push, the items are OK there:
Here is the view code:
<div formArrayName="items">
<div *ngFor="let item of form.controls.items.controls; let i=index" [formGroupName]="i" class="row item-index-{{ i }}">
<div class="form-group">
<div class="col-sm-2">
<input type="text" class="form-control" placeholder="Start" autocomplete="off" formControlName="start">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="Title" autocomplete="off" formControlName="title">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" placeholder="Category" autocomplete="off" formControlName="category" (keydown)="addRow($event.keyCode, i)">
</div>
<div class="col-sm-2">
<a class="btn btn-icon-only default">
<i class="fa fa-arrow-up"></i>
</a>
<a class="btn btn-icon-only default">
<i class="fa fa-arrow-down"></i>
</a>
<a class="btn btn-icon-only red">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</div>
</div>
Any idea why this happens?
In case someone has this problem but the cause is different, check if you're adding your controls correctly:
let arr = new FormArray([]);
arr.push(....); // Make sure you do this
arr.controls.push(....); // And not this!
I've encountered this issue once earlier when not inserting formgroup at the end of formarray. Seems Angular is having trouble tracking the index in template for some reason, and by using trackBy solved it. So try:
<div *ngFor="let item of form.get('items').controls; let i=index; trackBy:trackByFn"
[formGroupName]="i" class="row item-index-{{ i }}">
and in TS:
trackByFn(index: any, item: any) {
return index;
}

Angular 2 Form - disable submit when ngModel = empty obj

I have an Angular2 form that is created dynamically with a for loop. For this question I am concerned with the radio buttons in my form. The form is created in the HTML then from the TS I assign the ngModel of each input to an empty object. I want the submit button in my form to be disabled until a radio button is chosen:
<form (ngSubmit)="onNext(f)" #f="ngForm">
<div class="multi-choice-question-div radio-btn-div question_div"
*ngIf="question?.type === 'multi-choice' && !question?.isYesOrNo">
<div *ngFor="let answer of question?.answerDetails">
<input
type="radio"
class="display-none"
id="{{ answer?.answerId }}"
[(ngModel)]="ngModelObj['question_' + question.questionId]"
name="answerForQustion{{ question?.questionId }}"
[value]="answer"
required>
<label class="col-md-12 col-sm-12 multi-choice-label" for="{{ answer?.answerId }}">
<p class="q-text">{{ answer?.value }}</p>
</label>
</div>
</div>
<button class="btn btn-next"
type="submit"
*ngIf="currentSectionIndex < sectionsArr.length - 1"
[disabled]="!f.valid">
NEXT
</button>
</form>
Even when the client has not chosen a radio button, the form thinks that it is valid and I think this is because ngModel for the radio input is set = to {}.
How can I keep this same setup (because it is engrained deep into my component frontend and backend) but make the form invalid when the ngModel = {}
Two ways, call a function to check if the value is empty (potentially expensive, probably overcomplicated):
[disabled]="f.invalid || isEmpty(f.value)"
isEmpty(formValue) {
let x = JSON.parse(JSON.stringify(formValue));
return Object.getOwnPropertyNames(x).length === 0;
}
The stringify and parse together strip out any undefined keys (go ahead, console.log(formValue) and look at those undefined keys!)
Or you can check the form for dirty which indicates:
dirty : boolean A control is dirty if the user has changed the value
in the UI.
Note that programmatic changes to a control's value will not mark it
dirty.
[disabled]="!f.valid || !f.dirty"
https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#dirty-anchor
Plunker demo: http://plnkr.co/edit/14yQk2QKgBFGLMBJYFgf?p=preview

How to implement form validation with Angular JS and Bootstrap?

At a user registration web form I validate via ajax whether a username already exists in DB. When a username already exists, the corresponding input-text will go .has-error class.
Edit
I changed the ng-class attribute to {'has-error':signup.userUnavaliable()} but even though that the input is not seemly getting such class, in other words the mail input text is not getting red.
I place the directive at the wrapper as this is how the Bootstrap docs tell it.
This is how my form looks like now:
<form class="form-inline" role="form">
<div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="ContraseƱa" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable">Registrar</button>
</form>
And this is my Controller:
app.controller('SignUpController',function ($scope, $http) {
$scope.userUnavaliable = function() {
return $scope.unavaliable
}
$scope.print = function(msg) {
console.log(msg)
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
$scope.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
$scope.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
Also, I'm trying to disable the button and it's not gettin such effect, so I think my controller has any issue.
As given in bootstrap validation states, if you want your label color to be changed according to the validation state of the input, you will have to apply ng-class on that.
Here is the sample code that I had written a little while. Please note that to take advantage of Angular JS validation states on form elements, you need to provide name to all input types.
This code would turn the input box plus label color red or green depending upon the validation state.
<div class="form-group"
ng-class="( newProfileForm.email.$dirty ? (newProfileForm.email.$valid ? 'has-success has-feedback' : 'has-error has-feedback' ) : ' ')"
>
<label class="col-sm-4 control-label">Email</label>
<div class="col-sm-6">
<input type="email" name="email" class="form-control" ng-model="user.mail" ng-required='true'>
<!-- Invalid Span -->
<span ng-if='newProfileForm.email.$invalid && newProfileForm.email.$dirty' class="glyphicon glyphicon-remove form-control-feedback"></span>
<!-- Valid Span -->
<span ng-if='newProfileForm.email.$valid' class="glyphicon glyphicon-ok form-control-feedback"></span>
<p ng-show="newProfileForm.email.$invalid && newProfileForm.email.$dirty" class="bg-danger pad">Please enter valid email.</p>
</div>
</div>
[EDIT] Explanation for name attribute.
Angular makes use of name attribute to determine the state of the input control. So, if you have a input control with name username. Even your form should have a name for angular validation states.
AngularJS would use the fallowing variables to check its validation state.
formname.username.$valid = if username is alright according to validation rules.
formname.username.$invalid = if username is invalid
formname.username.$dirty = if user has edited the input box
formname.username.$pristine = if user has not edited the input box.
Angular makes use of name attribute for validaiton.
And if you want your button to be disabled depending upon the availability of the user.
Use something like
<button class="btn btn-default" ng-disabled="unavaliable">Submit</button>
try
<div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">

Categories

Resources