Filter with search and select inputs - javascript

I'm not getting any errors but I think I'm just missing something that I cannot see.
My API's are all working. I just wanted to be able to have a search bar to search the names and then a <select> element for searching through departments. Pretty sure my problem is something to do with the filteredList().
Employees.vue
<script>
<template>
<div class="container">
<div class="form-row align-items-center justify-content-center">
<div class="col-md-6">
<label>Name</label>
<input v-model="search" id="inputKeyword" name="inputKeyword" type="text" class="form-control mb-2 form-control-lg">
</div>
<div class="col-md-4">
<label>Department</label>
<select v-model="selectedDepartment" id="inputfilter" name="inputfilter" class="form-control mb-2 form-control-lg select-department">
<option v-for="department in departments" v-bind:key="department.name">
{{ department.name }}
</option>
</select>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-10">
<ul class="list-unstyled">
<employee v-for="employee in filteredList" :employee="employee" :key="employee.id"></employee>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
search: '',
selectedDepartment: '',
employees: [],
meta: null,
departments: [],
}
},
computed: {
filteredList() {
if(this.selectedDepartment == this.employees.department){
return this.employees == this.employees.filter(employees => {
return employees.department.toLowerCase().includes(this.selectedDepartment.toLowerCase())
})
}else{
return this.employees.filter(employees => {
return employees.name.toLowerCase().includes(this.search.toLowerCase())
})
}
}
},
methods: {
getEmployees(page){
axios('/employees').then((response) => {
this.employees = response.data.data
this.meta = response.data.meta
})
},
getDepartments(){
axios('/departments').then((response) => {
// console.log(response.data)
this.departments = response.data
})
},
},
mounted() {
this.getEmployees()
this.getDepartments()
}
}
</script>

Related

How do I use one input to control the other in vuejs

I need to find a way to basically show "per Month" in the assessments_period input if the assessments fee input has a typed-in value.
I've tried bindings and components but can't pull this off.
<div class="col-lg-6">
<div class="form-group">
<label>Assessment Fee <span class="note">C</span></label>
<input type="text" class="form-control" v-model="document.assessments_fee" placeholder="$">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Assessment Period <span class="note">C</span></label>
<input type="text" class="form-control" v-model="document.assessments_period" placeholder="(per month/quarter/etc.)">
</div>
</div>
data() {
return {
now: new Date().toISOString(),
document: {
assessments_fee: '',
assessments_period: '',
}
}
},
components: {
assessments_fee: function() {
if(this.assessments_fee != null || '') this.assessments_period = "per Month";
}
},
you can create a watcher for assessments_fee so when its not null assessments_period= 'per Month'.
Here is how you can do it:
new Vue({
el: '#app',
data() {
return {
now: new Date().toISOString(),
document: {
assessments_fee: '',
assessments_period: '',
}
}
},
computed: {
assessmentsFee() {
return this.document.assessments_fee
}
},
watch: {
assessmentsFee() {
this.document.assessments_fee ?
this.document.assessments_period = "per Month" :
this.document.assessments_period = ""
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="col-lg-6">
<div class="form-group">
<label>Assessment Fee <span class="note">C</span></label>
<input type="text" class="form-control" v-model="document.assessments_fee" placeholder="$">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Assessment Period <span class="note">C</span></label>
<input type="text" class="form-control" v-model="document.assessments_period" placeholder="(per month/quarter/etc.)">
</div>
</div>
</div>

Vuelidate errors return true but elements don't render

I have a contact form that uses vuelidate to validate fields. The problem is - the validation works, but the errors don't render.
$v.name.dirty is TRUE and $v.name.required is FALSE.
Logging $v.name.dirty && !$v.name.required returns TRUE which is the same condition in the v-if directive but the error elements still don't show.
However, when .$touch() is called and $v.name.dirty becomes true and $v.name.required false, anything I type in the input fields will show the errors.
JS:
import translationsBus from "../../app/translations";
export default {
name: "contactForm",
beforeMount() {
this.$store.dispatch("updateTranslations", translationsBus.translations);
},
data: function () {
return {
name: '',
email: '',
subject: '',
message: ' ',
errors: [],
isSuccessful: ''
}
},
mounted() {
var my_axios = axios.create({
baseURL: '/'
});
Vue.prototype.$http = my_axios;
},
computed: {
isLogged: function () {
return isLoggedOn;
},
shouldShowSubjectOption: function () {
return showSubjectOption;
},
translations: function () {
return this.$store.state.translations.translations;
},
},
methods: {
onContactUsClick: function onContactUsClick() {
const _this = this;
this.$v.$touch();
if (!this.$v.$error) {
let model = {
senderName: _this.name,
senderEmail: _this.email,
subject: _this.subject,
message: _this.message
};
this.$http.post('/home/contactus', model)
.then(response => {
console.log(response);
_this.isSuccessful = response.data;
})
.catch(e => {
console.log(e);
});
}
}
},
validations: {
email: {
required: required,
isValidEmail: function isValidEmail(value) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(value);
}
},
name: {
required: required
},
subject: {
required: required
},
message: {
required: required
}
}
}```
HTML:
<div v-bind:class="{ 'col-lg-6' : shouldShowSubjectOption, 'col-lg-12' : !shouldShowSubjectOption }">
<div id="form-contact">
<h1 class="lead">Get in touch...</h1>
<form class="text-center" >
<div class="form-group">
<label for="name">{{translations['contact_Form_Name']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<input type="text" class="form-control" name="senderName" id="senderName" v-model:bind="name" v-bind:placeholder="translations['contact_Form_NamePlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.name.$dirty && !$v.name.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
</div>
<div class="form-group">
<label for="email">{{translations['contact_Form_EmailAddress']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-envelope"></span></span>
<input type="email" class="form-control" name="senderEmail" id="senderEmail" v-model:bind="email" v-bind:placeholder="translations['contact_Form_EmailAddressPlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.email.$dirty && !$v.email.required">{{translations['shared_Validation_ReuiredField']}}</label>
<label class="control-label" v-if="$v.email.$dirty && $v.email.required && !$v.email.isValidEmail">{{translations['contact_Form_EmailAddressValidationMessage']}}</label>
</div>
</div>
<div class="form-group" v-if="shouldShowSubjectOption">
<label for="subject">{{translations['contact_Form_Subject']}}</label>
<select id="subject" name="subject" class="form-control" v-model:bind="subject" v-bind:title="translations['contact_Form_SubjectPickerText']">
<option value="service">1</option>{{translations['contact_Form_SubjectOption_GCS']}}
<option value="suggestions">2</option>{{translations['contact_Form_SubjectOption_Suggestions']}}
<option value="product">3</option>{{translations['contact_Form_SubjectOption_ProductSupport']}}
</select>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.subject.$dirty && !$v.subject.required" v-cloak>{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group">
<label for="name">{{translations['contact_Form_Message']}}</label>
<textarea name="message" id="message" class="form-control" v-model:bind="message" rows="9" cols="25"
placeholder="">{{translations['contact_Form_Message']}}</textarea>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.message.$dirty && !$v.message.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group" v-if="isLogged">
<div class="g-recaptcha" data-sitekey=""></div>
</div>
<button type="button" class="btn btn-primary btn-block" v-on:click="onContactUsClick" id="btnContactUs">{{translations['contact_Form_SendMessageButton']}}</button>
</form>
</div>
</div>
</div>
</div>
I expect error elements to appear on submit.

Why i can't filter local json file in this case (vuejs2)

Before i set vue cli-3 in my project, the filter could work. After I set it up, I cannot reach any result. What am I doing wrong? There isn't any error in the console. I'll share the codes below.
Thanks in advance.
<template>
<div id="preview" class="nested">
<div class="card-body" v-for="item in items" :key="item.id">
<h5 class="card-title">{{item.companyName}}</h5>
<p class="card-text">{{item.positionName}}</p>
<p class="card-text">{{item.cityName}}</p>
<p class="card-text">{{item.townName}}</p>
<p class="card-text">{{item.distance}}</p>
Go!
</div>
</div>
</template>
<script>
export default {
data() {
return {
filteredFounded: [],
founded: [],
items: [],
search: "",
show: false,
city: ""
};
},
created() {
this.$http
.get("http://www.json-generator.com/api/json/get/cguWKZoQMO?indent=2")
.then(res => {
return res.json();
})
.then(res => {
this.founded = res.items;
});
},
methods: {
setFounded() {
this.filteredFounded = this.founded.filter(items => {
return (
items.cityName.toLowerCase() === this.city.toLowerCase() &&
items.positionName.toLowerCase().match(this.search.toLowerCase())
);
});
}
}
};
</script>
i forgot add this code. sorry. everythings look fine but. Cannot read property 'filter' of undefined error fetch now.
<template>
<div id="app" class="nested">
<div class="card w-50">
<div class="search">
<input type="text" class="job" v-model="search" placeholder="Job...">
<select name="" class="city" id="">
<option value="Seçiniz">Seçiniz</option>
<option value="İstanbul">İstanbul</option>
<option value="Ankara">Ankara</option>
<option value="İzmir">İzmir</option>
<option value="Çanakkale">Çanakkale</option>
</select>
</div>
<div class="find">
<button v:on-click="setFounded">Find!</button>
</div>
</div>
</div>
Your problem is not related to Vue Cli 3.x, you had done some mistakes in the promise scope such as return res.json() and this.founded = res.items; but the res object have the following keys :config data headers request status and statusText.
In this situation we need only the data property which is an array of objects (items), so change return res.json() to return res.data and this.founded = res.items; to this.founded = res.data;
add v-model="city" to the select as follow <select name="" class="city" id="" v-model="city"> and you had written v:on-click incorrectly, change it to #click
Finally change return ( items.cityName.toLowerCase() === this.city.toLowerCase() && items.positionName.toLowerCase().match(this.search.toLowerCase()) ); to return ( items.cityName === this.city && items.positionName===this.search );

How can i fetch value in JSON file by tag and city options with vue?

Firstly my english is not good. Sorry about that.
1-) My case is: when I write the necessary info into the gaps,- for example job name for one gap and for the other gap the city name(like istanbul)- I want to see the jobs in that city on page.
2-) Also, when i use the box to search for something, i need to use capital letters in order to see result. I want to see the result no matter how i type the letter, capital or not, How can i achieve this?
Thanks for all help.
this is full code
var app = new Vue({
el: "#app",
data: {
founded: [],
search: "",
show: false,
city: ""
},
created() {
fetch("job.json")
.then(res => {
return res.json();
})
.then(res => {
this.founded = res.items;
});
},
computed: {
filteredFounded: function() {
return this.founded.filter(items => {
return (
items.cityName === this.city && items.positionName.match(this.search)
);
});
}
}
});
<div class="header">
<h4>Get Job</h4>
</div>
<div id="app" class="nested">
<div class="card w-50">
<div class="search">
<input type="text" class="job" v-model="search" placeholder="Job..." #keypress.enter="founded">
<select name="" class="city" id="" v-model="city">
<option value="Seçiniz">Seçiniz</option>
<option value="İstanbul">İstanbul</option>
<option value="Ankara">Ankara</option>
<option value="İzmir">İzmir</option>
<option value="Çanakkale">Çanakkale</option>
</select>
</div>
<div class="find">
<button #click="show = true">Find!</button>
</div>
<div class="card-body" v-show="show" v-for="items in filteredFounded">
<h5 class="card-title">{{items.companyName}}</h5>
<p class="card-text">{{items.positionName}}</p>
<p class="card-text">{{items.cityName}}</p>
<p class="card-text">{{items.townName}}</p>
<p class="card-text">{{items.distance}}</p>
Go!
</div>
</div>
</div>
and this is job.json file
You can achieve this by first turning the required data into lower or uppercase letters. You do this using the toLowerCase() or toUpperCase() functions and then compare the data. For example, you can do something like this.
computed: {
filteredFounded: function () {
return this.founded.filter(items => {
return (
items.cityName.toLowerCase() === this.city.toLowerCase() && items.positionName.toLowerCase().match(this.search.toLowerCase())
);
});
}
}

passing data between components in vuejs

I've got my expense tracker app. I've got problem with adding Expense.
I've got two components responsible for this: addCategory.vue and selectCategory.vue.
This is my selectCategory.vue component:
<template>
<div>
<select class="custom-select" #selected="this.$emit('select-cat',category)">
<option v-for="category in categories">{{ category.title }}</option>
</select>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
categories: [],
errors: []
}
},
created() {
axios.get(`http://localhost:3000/categories`)
.then(response => {
this.categories = response.data;
console.log(response.data);
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
and this is my addExpense.vue component:
<template>
<div class="card">
<div class="card-header">
<h4>Dodaj nowy wydatek</h4>
</div>
<form v-on:submit.prevent="addExpense">
<div class="card-body">
<div class="form-group">
<label for="expense-name">Nazwa wydatku</label>
<input type="text" class="form-control" id="expense-name" v-model="Expense.title">
</div>
<div class="form-group">
<label for="expense-amount">Wartość</label>
<input type="number" class="form-control" id="expense-amount" v-model="Expense.amount">
</div>
<div class="form-group">
<label for="expense-date">Data wydatku</label>
<input type="date" class="form-control" id="expense-date" v-model="Expense.date">
</div>
<div class="form-group">
<label for="expense-category">Kategoria</label>
<select-category #select-cat="chooseCategory" v-model="Category.id"></select-category>
</div>
<br>
<div class="form-group">
<button class="btn btn-primary" #click="showAlert">Dodaj nowy wydatek</button>
</div>
</div>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios';
import selectCategory from './selectCategory.vue';
export default {
components: {
'select-category': selectCategory
},
data(){
return {
Expense: {
title:'',
amount: '',
date:'',
categoryId:''
},
}
},
methods : {
chooseCategory(){
this.Expense.categoryId = this.Category.id
},
showAlert(){
this.$alert.success({
message: 'Wydatek dodany poprawnie'
})
},
addExpense(){
let newExpense = {
title : this.Expense.title,
amount : this.Expense.amount,
date : this.Expense.date,
categoryId: this.Expense.categoryId
}
console.log(newExpense);
axios.post(`http://localhost:3000/expenses`, newExpense)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
}
}
</script>
I need help because when I try to add the Expense, field with 'categoryId' remains empty.
I use Events to pass the name of categories but I dont know how to add category.id to Expense.
The issues in your codes:
you need to add one data property to save which option the user selected, so add one data property=selectedCategory
you didn't bind the value for the options of the select, and you didn't bind the value of the select, so add v-model="selectedCategory" for <select> and add :value="category" for <option>
It seems you bind wrong event (event=selected more likely is the event name you customized) for <select>, change to #change="selectChange(selectedCategory)"
Finally, in addExpense.vue, listen event=select-cat.
Like below demo:
Vue.config.productionTip = false
Vue.component('select-category', {
template: `<div>
<select class="custom-select" v-model="selectedCategory" #change="selectChange(selectedCategory)">
<option v-for="category in categories" :value="category">{{ category.title }}</option>
</select>
</div>`,
data() {
return {
categories: [],
errors: [],
selectedCategory: null
}
},
mounted() {
this.categories = [
{'id':1, 'title': 'abc'},
{'id':2, 'title': 'xyz'}
]
},
methods: {
selectChange: function(newCatetory) {
this.$emit('select-cat',newCatetory)
}
}
})
new Vue({
el: '#app',
data() {
return {
categorySelected: null
}
},
watch: {
categorySelected: function (newVal, oldVal) {
console.log('changed to ' + newVal.id + ' from ' + (oldVal ? oldVal.id : oldVal))
}
},
methods:{
chooseCategory: function(data) {
this.categorySelected = data
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div class="form-group">
<label for="expense-category">Kategoria</label>
<select-category #select-cat="chooseCategory($event)"></select-category>
</div>
</div>

Categories

Resources