how to validate two dropdowns depends upon selection? - angular10

I have two Dropdowns first dropdown 1 to 23 hours and the second dropdown also 1 to 23 hours.
If I select the first Dropdown is 4.the second drop-down is higher than the first dropdown selected value. how to do that

This is the solution for your concern. I have used the form if you are not used form then remove it and take the normal angular control.
HTML
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<select formControlName="firstDropdown" class="form-control" (change)="firstDropDownChange($event)">
<option *ngFor="let value of values" [value]="value">
<span>{{ value }}</span>
</option>
</select>
<select formControlName="secondDropdown" class="form-control" (change)="secondDropDownChange($event)">
<option *ngFor="let value of values1" [value]="value">
<span>{{ value }}</span>
</option>
</select>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">
Submit
</button>
</form>
TS
values: any = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];
values1: any = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];
firstDropdown: any = 1;
secondDropdown: any = 1;
form: FormGroup;
constructor() {
this.form = new FormGroup({
firstDropdown: new FormControl(1),
secondDropdown: new FormControl(1),
});
}
firstDropDownChange(event) {
this.values1 = this.values.filter(
(data) => parseInt(event.target.value) <= data
);
console.log(this.values1);
this.form.controls['secondDropdown'].setValue(parseInt(this.values1[0]));
}
secondDropDownChange(event) {}
submit() {}

Related

Laravel/Livewire dynamic dropdown not sending the selected value

Using Laravel 8 + Livewire:
I was following this tutorial of creating a dynamic dropdown: https://www.itsolutionstuff.com/post/laravel-livewire-dependant-dropdown-exampleexample.html
I have this dropdown component:
public $suppliers;
public $beans;
public $selectedSupplier = NULL;
public function mount()
{
$this->suppliers = Supplier::whereHas('greenBeans')->get();
$this->beans = collect();
}
public function render()
{
return view('livewire.admin.supplier-beans-dropdown')->layout('layouts.admin.livewire');
}
public function updatedSelectedSupplier($supplier)
{
if (!is_null($supplier)) {
$this->selectedSupplier = Supplier::find($supplier);
$this->beans = $this->selectedSupplier->greenBeans;
}
}
The component's blade:
<div>
<div class="form-group">
<label for="supplier" class="col-md-4 form-label">Supplier</label>
<select wire:model.lazy="selectedSupplier" class="form-control">
<option value="" selected>Select Supplier</option>
#foreach($suppliers as $supplier)
<option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
#endforeach
</select>
</div>
#if (!is_null($selectedSupplier))
<div class="form-group">
<label for="bean" class="form-label">Green Bean</label>
<select class="form-control" name="bean" wire:model.lazy="selectedBean">
<option value="" selected>Select Green Bean...</option>
#foreach($beans as $bean)
<option value="{{ $bean->id }}">{{ $bean->name }}</option>
#endforeach
</select>
</div>
#endif
I have an other component that needs to call this dropdown. So in this parent component I have this var: $selectedSupplier and in the view I call the dropdown component:
#livewire('admin.supplier-beans-dropdown')
When I select a supplier and submit the form, the selectedSupplier is null.
So how do I use this dropdown in different components?
How do I send the selected value to the parent component?
check this first I think you have some errors here. you have:
public function updatedSelectedSupplier($supplier)
{
if (!is_null($supplier)) {
$this->supplier = Supplier::find(supplier); --> typo error here???
$this->beans = $supplier->greenBeans; --> $supplier parameter is an ID???
}
}
and I think it should be:
if (!is_null($supplier)) {
$this->supplier = Supplier::find($supplier);
$this->beans = $this->supplier->greenBeans;
}

How to get object relation inside <option> loop in Vue?

Let's go to the point of the question. I have a selection component, it looks like this:
<template>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="category_id">
Product Category
</label>
<select
name="category_id"
id="category_id"
:class="form.errors.has('category_id') ? 'form-control is-invalid' : 'form-control'"
v-model="form.sharedState.category_id">
<option value="" disabled hidden>Select Category</option>
<option
v-for="category in categories"
:key="category.id"
v-text="category.name"
:value="category.id"
#click="$emit('category-selected', category.sub_categories)">
</option>
</select>
<small
class="form-text text-danger"
v-if="form.errors.has('category_id')"
v-text="form.errors.get('category_id')"></small>
</div>
</div>
<div class="col-md-6">
<div
class="form-group"
v-if="revealSubCategory"
#category-selected="show">
<label for="category_id">
Sub Category
</label>
<select
name="sub_category_id"
id="sub_category_id"
:class="form.errors.has('sub_category_id') ? 'form-control is-invalid' : 'form-control'"
v-model="form.sharedState.sub_category_id">
<option value="" disabled hidden>Select Sub Category</option>
<option
v-for="subcategory in subcategories"
:key="subcategory.id"
v-text="subcategory.name"
:value="subcategory.id">
</option>
</select>
<small
class="form-text text-danger"
v-if="form.errors.has('category_id')"
v-text="form.errors.get('category_id')"></small>
</div>
</div>
</div>
</template>
<script>
import BaseCard from './BaseCard.vue';
export default {
components: {
BaseCard
},
data() {
return {
categories: [],
revealSubCategory: false,
subcategories: [],
form: new Form({
sharedState: product.data
})
}
},
mounted() {
this.getCategories();
},
methods: {
getCategories() {
axios.get('categories')
.then(({data}) => this.categories = data);
},
show(subcategories) {
this.revealSubCategory = true;
this.subcategories = subcategories
}
}
}
</script>
And a select sub category input (it is there on the second column) which is will be displayed once the user has selected one of the categories options. Each category option has relation to sub categories taken from the API.
How can I get the sub categories and display the input? I already tried #change on the select tag but I can't pass the sub category object because it is outside the loop. And #click event seems to be not working in an option tag.
You can watch the v-model of the first select and change subcategory.
watch:{
"form.sharedState.category_id": function (val) {
// update subcategories here
}

Vue.js - Use v-for with dynamic range value

Maybe I'm going about this the wrong way ... but I'm trying to use a v-for loop to duplicate/remove a custom component x times. x is decided by a <select> field above. What I have works on the initial page load, but then when you select a different option, only one custom component is displayed (although x is updated). Does anyone have any idea what I am doing wrong?
// here is the select field that defines the number of enrolling students
<select name="number_students_enrolling" v-model="formFields.numberStudentsEnrolling">
<option value="" default selected></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// here is the custom component I'm trying to duplicate/remove dynamically
<div class="students-container">
<student v-for="n in formFields.numberStudentsEnrolling" :key="n" v-bind:index="n" >
</student>
</div>
// here is the custom component
Vue.component('student', {
props: ["index"],
template: `
<div class="input--student">
<div class="input--half">
<label>
<span class="d-block">
Student {{ index }} Name <span class="field--required">*</span>
</span>
<input type="text">
</label>
</div>
<div class="input-wrap input--half">
<label>
<span class="d-block">
Student {{ index }} DOB <span class="field--required">*</span>
</span>
<input type="text">
</label>
</div>
</div>
`
})
// Here is the Vue.js instance
var test = new Vue({
el: '#test',
data: {
formFields: {
numberStudentsEnrolling: 3
}
}
});
v-for needs a Number, but you're giving it a string (the selected value). Convert it to a Number so v-for will treat it as a range from 1 to N:
<div class="students-container">
<student
v-for="n in Number(formFields.numberStudentsEnrolling)"
:key="n"
v-bind:index="n">
</student>
</div>
For completeness, another approach (per #HusamIbrahim) is to annotate the v-model reference with .number, which will automatically do the conversion.
<select
name="number_students_enrolling"
v-model.number="formFields.numberStudentsEnrolling"
>
Here's a codesandbox: https://codesandbox.io/s/xzy6or9qo

remove option from second select if already selected [Ordered multiple selection]

I had select option repeater.
What I want is that when I selected johndoe at the first option, it will no longer display on the second select option.
here's my html
<div id="app">
<h1>Vue JS Multiple Fields Repeater</h1>
<div class="col-sm-6">
<div class="panel panel-default relative has-absolute" v-for="(field, index) in users.usersRepeater">
<button #click="addUsersField" type="button">
Add
</button>
<button #click="deleteUsersField(index)" v-if="field != 0" type="button">
Delete
</button>
<div class="panel-body has-absolute">
<div class="form-group">
<label for="users" class="control-label col-sm-3 text-left">Users {{field}}</label>
<select :name="'users'+index"
class="form-control"
id="users">
<option value="" hidden>Select User</option>
<option value="1">John Doe</option>
<option value="2">Mark Doe</option>
<option value="3">Mae Doe</option>
<option value="4">John Smith</option>
<option value="5">Mae Smith</option>
</select>
</div>
</div>
</div>
</div>
</div>
here's my vue.js
new Vue({
el: '#app',
data: {
users: {
usersRepeater: [{ user: '' }]
}
},
methods: {
addUsersField: function() {
this.users.usersRepeater.push({
user: ''
});
},
deleteUsersField: function(index) {
this.users.usersRepeater.splice(index, 1);
},
}
});
here's the fiddle -> https://jsfiddle.net/0e3csn5y/23/
Ok I have this working now. I liked the question because making an ordered selection is a generic case. But, for me anyway, it wasn't straightforward. The breakthrough was realising that, when you number the choices, the whole state of the component could be encapsulated in one array, allUsers. Available users and choices then become computed properties, based on this array. Moral of the story: get your store right, with no interactions between elements of the store.
My answer weighs in at 130 lines. How long and hard would this be without Vue? Mind boggles.
Stack wants me to post some code, so here's the computed property that generates an array of choices made, in order of their priority, from the all users array...
choices(){
return this.store.allUsers.map((aUser,index)=>{
if(aUser.selection != null)
return {idxAllUsers : index, selection: aUser.selection};
else
return null;
})
.filter(aSelection=>aSelection != null)
.sort((a,b)=>{return a.selection - b.selection})
.map(a=>a.idxAllUsers);
},
I found this one very helpful.

vuejs set a radio button checked if statement is true

I am trying to make a radio button checked using vuejs v-for only if my if-statement is true. Is there a way to use vuejs' v-if/v-else for this type of problem?
in php and html I can achieve this by doing the following:
<input type="radio" <? if(portal.id == currentPortalId) ? 'checked="checked"' : ''?>>
Below is what I have so far using vuejs:
<div v-for="portal in portals">
<input type="radio" id="{{portal.id}}" name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
v-if="{{portal.id == currentPortalId}}"
checked="checked">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
I know the v-if statement here is for checking whether to show or hide the input.
Any help would be very much appreciated.
You could bind the checked attribute like this:
<div v-for="portal in portals">
<input type="radio"
id="{{portal.id}}"
name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
:checked="portal.id == currentPortalId">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
Simple example: https://jsfiddle.net/b4k6tpj9/
Maybe someone finds this approach helpful:
In template I assign each radio button a value:
<input type="radio" value="1" v-model.number="someProperty">
<input type="radio" value="2" v-model.number="someProperty">
Then in the component I set the value, i.e:
data: function () {
return {
someProperty: 2
}
}
And in this case vue will select the second radio button.
You can follow below option if you can adjust with your logic:
<div class="combination-quantity">
<input type="radio" value="Lost"
v-model="missing_status">
<label for="lost">Lost</label>
<br>
<input type="radio" value="Return Supplier" v-model="missing_status">
<label for="return_supplier">Return Supplier</label>
</div>
Value for missing_status could be "Lost" or "Return Supplier" and based on the value radio option will be get selected automatically.
Below is an example of keeping track of the selected radiobutton, by
applying a value binding to the object (:value="portal") and
applying a v-model binding to the currently selected object (v-model="currentPortal").
The radiobutton will be checked automatically by Vue, when the two match (no :checked binding necessary!).
Vue 3 with composition API
Vue.createApp({
setup() {
const portals = [{
id: 1,
name: "Portal 1"
}, {
id: 2,
name: "Portal 2"
}];
const currentPortal = portals[1];
return {
portals,
currentPortal
}
}
}).mount("#app");
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<template v-for="portal in portals">
<input
type="radio"
:id="portal.id"
name="portalSelect"
:value="portal"
v-model="currentPortal">
<label :for="portal.id">{{portal.name}}</label>
</template>
</div>
I would like to point out a few options when dealing with radios and vue.js. In general if you need to dynamically bind an attribute value you can use the shorthand binding syntax to bind to and calculate that value. You can bind to data, a computed value or a method and a combination of all three.
new Vue({
el: '#demo',
data() {
return {
checkedData: false,
checkedGroupVModel: "radioVModel3", //some defaul
toggleChecked: false,
recalculateComputed: null
};
},
computed: {
amIChecked() {
let isEven = false;
if (this.recalculateComputed) {
let timeMills = new Date().getMilliseconds();
isEven = timeMills % 2 === 0;
}
return isEven;
}
},
methods: {
onToggle() {
this.toggleChecked = !this.toggleChecked;
return this.toggleChecked;
},
mutateComputedDependentData() {
this.recalculateComputed = {};
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="demo">
<div>
<div>
<span>Simple Radio Group - Only one checked at a time. Bound to data.checkedData</span><br>
<label>Radio 1 - inverse of checkedData = {{!checkedData}}
<input type="radio" name="group1" value="radio1" :checked="!checkedData">
</label><br>
<label>Radio 2 - checkedData = {{checkedData}}
<input type="radio" name="group1" value="radio2" :checked="checkedData">
</label><br>
<span>Understanding checked attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked</span>
</div>
<br>
<div>
<span>Simple Radio - Checked bouned to semi-random computed object</span><br>
<label>Radio 1: {{amIChecked}}
<input type="radio" :checked="amIChecked">
</label>
<label>Recalculate Computed Value
<button type="button" #click="mutateComputedDependentData">Click Me Several Times</button>
</label>
</div>
<br>
<div>
<span>Simple Radio Group - v-model bound value = {{checkedGroupVModel}}</span><br>
<label>Simple Radio 1:
<input type="radio" name="vModelGroup" value="radioVModel1" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 2:
<input type="radio" name="vModelGroup" value="radioVModel2" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 3:
<input type="radio" name="vModelGroup" value="radioVModel3" v-model="checkedGroupVModel">
</label>
</div>
<br>
<div>
<span>Simpe Radio - click handler to toggle data bound to :checked to toggle selection</span><br>
<label>Toggle Radio = {{toggleChecked}}
<input type="radio" :checked="toggleChecked" #click='onToggle()'>
</label>
</div>
</div>
</div>