I have a svelte component where i want to connect a selected input with a declared attribute.
My problem is that the binding of the selected value of status to the attribute'status' declared in 'flightschedules' doesnt work.
The options are from the attribute questions: on-time, delayed, cancelled
Can somebody help me please ?
Here is my code (its a component to create form, e.g create a flightschedule):
<script>
import axios from "axios";
import { onMount } from "svelte";
export let params = {};
let flightschedule = {
timeofdeparture: "",
flightnumber: "",
gatenumber: "",
status: "",
privatejetline_id: null,
};
let questions = [
{ text: "on-time" },
{ text: "delayed" },
{ text: "cancelled" },
];
let selected;
let privatejetline_ids = [];
onMount(() => {
getPrivateJetLineIds();
selected = params.status;
});
function getPrivateJetLineIds() {
axios
.get("http://localhost:8080/flights/privatejetline")
.then((response) => {
privatejetline_ids = [];
for (let privatejetline of response.data) {
privatejetline_ids.push(privatejetline.id);
}
flightschedule.privatejetline_id = privatejetline_ids[0];
});
}
function addFlightSchedule() {
axios
.post("http://localhost:8080/flights/flightschedule", flightschedule)
.then((response) => {
alert("Flight Schedule added");
console.log(response.data);
})
.catch((error) => {
console.log(error);
alert(error);
});
}
</script>
<div class="mb-3">
<label for="" class="form-label">Status</label>
<select bind:value={flightschedule.status} class="from-select">
<option value="" disabled>-- Select Status --</option>
{#each questions as question}
<option value={selected} selected={selected===flightschedule.status}>{question.text}</option>
{/each}
</select>
</div>
Actually, no need for selected variable, just bind the flightschedule.status. Try following in REPL.
<script>
let flightschedule = {
timeofdeparture: "",
flightnumber: "",
gatenumber: "",
status: "",
privatejetline_id: null,
};
let questions = [
{ text: "on-time" },
{ text: "delayed" },
{ text: "cancelled" },
];
$: console.log('---->', flightschedule.status)
</script>
<div class="mb-3">
<label for="" class="form-label">Status</label>
<select bind:value={flightschedule.status} class="from-select">
<option value="" disabled>-- Select Status --</option>
{#each questions as question}
<option value={question.text}>{question.text}</option>
{/each}
</select>
</div>
<option value={selected} this line can’t be right. You’re binding all three options to the same value.
You probably want following:
<select bind:value={selected} class="from-select">
<option value="" disabled>-- Select Status --</option>
{#each questions as question}
<option value={question.text}>{question.text}</option>
{/each}
</select>
Related
I am building a booking Hotel application and I am trying to achieve search by multiple inputs with react.js. I tried with the code below but I have two errors :
first error: that whenever I change the value of type room or the number of guests I get the result with the previous state, I always get the result with the previous state.the search is working fine but it using the previous state.
second error: How to achieve intersection of the two results of objects.
Or if anyone can come with a better solution.
import React, { useState } from 'react';
import './SearchPage.css';
import RoomList from './RoomList';
import { v4 as uuidv4 } from 'uuid';
const SearchPage = () => {
const Rooms = [
{
id: uuidv4(),
description: 'Chnambre du luxe 1',
size: 250,
guests: '4',
roomType: 'family room',
pets: false,
picture: 'pictures/pic.jfif',
price: 1000,
},
{
id: uuidv4(),
description: 'chambre du lux2',
picture: 'pictures/pic2.jfif',
price: 2000,
size: 300,
guests: '4',
roomType: 'single room',
pets: true,
},
{
id: uuidv4(),
description: 'chambre du luxe 3',
picture: 'pictures/pic2.jfif',
price: 2500,
size: 350,
guests: '2',
roomType: 'family room',
pets: true,
},
];
const [foundRooms, setFoundRooms] = useState(Rooms);
const [roomType, setRoomType] = useState('All');
const [guestNumber, setGuestNumber] = useState('0');
const HandleGuestNumber = (state) => {
const results = Rooms.filter((room) => room.guests === state);
return results;
};
const HandleRoomType = (state) => {
let results = [];
results = Rooms.filter((room) => {
let rooms = room.roomType.match(state);
return rooms;
});
return results;
};
const HandleOnChange = (event) => {
switch (event.target.name) {
case 'roomType':
setRoomType(event.target.value);
break;
case 'guestNumber':
setGuestNumber(event.target.value);
break;
default:
console.log(`Sorry, we are out of.`);
}
let foundRooms = HandleRoomType(roomType) && HandleGuestNumber(guestNumber);
setFoundRooms(foundRooms);
};
return (
<div>
<div className="SearchPage">
<h1> Search</h1>
</div>
<div className="SearchContainers">
<div className="SearchItem">
<span>Room Type : </span>
<select onChange={HandleOnChange} name="roomType">
<option value="All">All</option>
<option value="family room">Family Room</option>
<option value="single room">Single Room</option>
<option value="Luxiourious Family Room">
Luxiourious Family Room
</option>
<option value="Luxiourious Single Room">
Luxiourious Single Room
</option>
</select>
</div>
<div className="SearchItem">
<span> Guests : </span>
<select onChange={HandleOnChange} name="guestNumber">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
);
};
export default SearchPage;
In your HandleOnChange function, you are doing this:
let foundRooms = HandleRoomType(roomType) && HandleGuestNumber(guestNumber);
setFoundRooms(foundRooms);
That is almost certainly not doing what you think it is doing.
Since HandleRoomType always returns an array, foundRooms always evaluates to HandleGuestNumber(guestNumber).
It sounds like you want foundRooms to be the rooms that are included in the arrays returned by both HandleRoomType and HandleGuestNumber.
One way you could do that is by doing another filter.
const roomsMatchingType = HandleRoomType(roomType)
const roomsMatchingGuestNumber = HandleGuestNumber(guestNumber)
const intersection = Rooms.filter(room => roomsMatchingType.some(r => r.id === room.id) && roomsMatchingGuestNumber.some(r => r.id === room.id))
I want to make the first value of time Object as a default value for my dropdown. Whenever user enter the website, the first value has been selected as my default value. However, my current code only display the value but not selected yet on vue data. How can I do that?
time Object:-
{ "1290_1320":"21:30 - 22:00",
"1320_1350":"22:00 - 22:30",
"1350_1380":"22:30 - 23:00"
}
Dropdown HTML:-
<div class="form-group col-md-8">
<select id="pickup" class="form-control" #change.prevent="changeTime($event)">
<option selected="selected" v-for="(time, i) in this.timeslots" :key="i"
:value="time">{{time}}</option>
</select>
</div>
Vue:-
export default {
data() {
return {
selectedTime: null
}
},
methods: {
changeTime(event) {
this.selectedTime = event.target.options[event.target.options.selectedIndex].text;
}
Dropdown javascript:-
// remove "selected" from any options that might already be selected
$('#pickup option[selected="selected"]').each(
function() {
$(this).removeAttr('selected');
}
);
// mark the first option as selected
$("#pickup option:first").attr('selected','selected');
It depends on your particular usecase but generally you can do something like this:
<div class="form-group col-md-8">
<select id="pickup" v-model="selectedTime" class="form-control">
<option v-for="(timeValue, timeID) in timeslots" :key="timeID" :value="timeID">{{ timeValue }}</option>
</select>
</div>
<script>
import axios from 'axios';
export default
{
name: 'MyDropDown',
data()
{
return {
selectedTime: null,
timeSlots: {},
}
},
created()
{
this.fetchData();
},
methods:
{
fetchData()
{
axios.get('/api/getTimeSlots').then(response =>
{
this.timeSlots = response.data;
this.selectedTime = Object.keys(response.data)[0];
});
},
}
}
I have JSON file like this
[
{
"id": 1,
"country": "Afghanistan",
"city": ["Eshkashem","Fayzabad","Jurm","Khandud"]
},
{
"id": 2,
"country": "Italy",
"city": ["Milano","Rome","Torino","Venezia"]
}
]
and I want to iterate through array placed in the city. Idea is to have two selects, where the first select is reserved for countries and the second is reserved for cities. Whenever the user selects a country, I want to populate the second select with a list of cities. Problem is that I receive only one array of all cities for that country. Here is my code:
export default class DiffCountries extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
contacts: [],
selectedCountry: [],
selectedCity: []
}
}
onChangeHandler = (event) => {
const test = CountriesData[event.target.value - 1];
this.setState({
selectedCountry: test,
selectedCity: this.state.selectedCountry.city
})
console.log(this.state.selectedCity);
}
render() {
const { contacts } = this.state;
return (
<div>
<select name="" id="" onChange={this.onChangeHandler}>
{CountriesData.map(item => {
const { id, country } = item;
return <option key={id} value={id}>{country}</option>
})}
</select>
<select name="" id="">
{this.state.selectedCountry !== undefined ?
<option value="">{this.state.selectedCountry.city}</option> :
null
}
</select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
And here is the screenshot of my problem
Thank you in advance!
You need to use map() on the city array.
<select name = "" id = "" > {
this.state.selectedCountry !== undefined ?
this.state.selectedCountry.city.map((x,i) => <option value={x} key={i}>{x}</option>)
:null
}
</select>
You need to iterate through the array.
this.state.selectedCountry.city.map((city, index) => {
return <option value={city} key={index}>{city}</option>
})
Be aware, that using the index as a key is considered an anti pattern. You could use the name of the city as a key as well. E.g.:
this.state.selectedCountry.city.map(city => {
return <option value={city} key={city}>{city}</option>
})
edit to add link to mdn docs as suggested in comments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Example:
const CountriesData = [
{
id: 1,
country: 'Afghanistan',
city: ['Eshkashem', 'Fayzabad', 'Jurm', 'Khandud'],
},
{
id: 2,
country: 'Italy',
city: ['Milano', 'Rome', 'Torino', 'Venezia'],
},
];
class DiffCountries extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedCountry: null,
};
}
onChangeHandler = event => {
const selectedCountry = CountriesData[event.target.value - 1];
this.setState({
selectedCountry,
});
};
render() {
const { selectedCountry } = this.state;
return (
<div>
<select
name="country"
defaultValue="country"
onChange={this.onChangeHandler}
>
<option disabled value="country">
Select country
</option>
{CountriesData.map(({ id, country }) => (
<option key={id} value={id}>
{country}
</option>
))}
</select>
{selectedCountry && (
<select name="city" defaultValue="city">
<option disabled value="city">
Select city
</option>
{selectedCountry.city.map(item => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
)}
</div>
);
}
}
ReactDOM.render(<DiffCountries />, document.getElementById('container'));
I have a issue on my project. Its repeated item on filter list.
I want remove all duplicate items on my list.
output result:
export default {
name: "ShowBlogs",
data() {
return {
blogs: [],
search: "",
UnitType: "",
PropertyName: "",
areCommunity: "",
AdType: ""
};
},
created() {
this.$http.get("http://localhost:3000/Listing").then(function(data) {
console.log(data);
this.blogs = data.body;
});
},
computed: {
filteredList() {
const { blogs, search, UnitType } = this;
return this.blogs
.filter(blog => blog.Unit_Type.includes(this.UnitType))
.filter(blog => blog.Community.includes(this.areCommunity))
.filter(blog => blog.Ad_Type.includes(this.AdType));
},
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<select
v-model="PropertyName"
id="formInput200"
class="form-control"
value="Buildingname"
>
<option disabled value>Building Name</option>
<option
v-for="blog in blogs"
v-bind:value="blog.Property_Name"
:key="blog.id"
>{{ blog.Property_Name}}</option>
</select>
How can I remove this from my list?
Its working on this code
Thank You #Dave
enter image description here
<select
v-model="UnitType"
id="UnitType"
class="form-control"
aria-placeholder="Property type"
>
<option disabled value>Property Type</option>
<option
v-for="blog in filteradtype"
v-bind:value="blog.Unit_Type"
:key="blog.id"
>{{ blog.Unit_Type}}</option>
</select>
filteradtype() {
return _.uniqBy(this.blogs, function(u) {
return u.Unit_Type;
});
},
I'm using vue js for my application in select option input..I need to set default value should be selected in the drop down and while on change i would like to call two functions ..
I'm new to vue js..
My Code :
var listingVue = new Vue({
el: '#mountain',
data:{
formVariables: {
country_id: '',
mountain_id: '',
peak_id: ''
},
countrylist:[],
mountainlist:[],
},
ready: function() {
var datas = this.formVariables;
this.getCountry();
},
methods: {
getCountry: function()
{
this.$http.get(baseurl+'/api/v1/device/getCountry',function(response)
{
this.$set('countrylist',response.result);
//alert(jQuery('#country_id').val());
});
},
getMountain: function(country_id)
{
var datas = this.formVariables;
datas.$set('country_id', jQuery('#country_id').val() );
postparemeters = {country_id:datas.country_id};
this.$http.post(baseurl+'/api/v1/site/getMountain',postparemeters,function(response)
{
if(response.result)
this.$set('mountainlist',response.result);
else
this.$set('mountainlist','');
});
},
});
<select
class="breadcrumb_mountain_property"
id="country_id"
v-model="formVariables.country_id"
v-on="change:getMountain(formVariables.country_id);">
<option
v-repeat = "country: countrylist"
value="#{{country.id}}" >
#{{country.name}}
</option>
</select>
With vue 2, the provided answer won't work that well. I had the same problem and the vue documentation isn't that clear concerning <select>. The only way I found for <select> tags to work properly, was this (when talking of the question):
<select v-model="formVariables.country_id">
<option v-for = "country in countrylist" :value="country.id" >{{country.name}}</option>
</select>
I assume, that the #-sign in #{{...}} was due to blade, it should not be necessary when not using blade.
In VueJS 2 you can bind selected to the default value you want. For example:
<select
class="breadcrumb_mountain_property"
id="country_id"
v-model="formVariables.country_id"
v-on:change="getMountain(formVariables.country_id);">
<option
v-for = "country in countrylist"
:selected="country.id == 1"
:value="country.id" >
{{country.name}}
</option>
</select>
So, during the iteration of the countryList, the country with the id 1 will be selected because country.id == 1 will be true which means selected="true".
UPDATED:
As Mikee suggested, instead of v-on="change:getMountain(formVariables.country_id);" there is a new way to for binding events. There is also a short form #change="getMountain(formVariables.country_id);"
You should use the 'options' attribute in place of trying to v-repeat <option></option>:
VM
data: {
countryList: [
{ text:'United States',value:'US' },
{ text:'Canada',value:'CA' }
]
},
watch: {
'formVariables.country_id': function() {
// do any number of things on 'change'
}
}
HTML
<select
class="breadcrumb_mountain_property"
id="country_id"
v-model="formVariables.country_id"
options="countryList">
</select>
You can use select in this way. Remember to use array in v-for.
<select v-model="album.primary_artist">
<option v-for="i in artistList" :key="i.id" :value="i.name">
{{ i.name }}
</option>
</select>
You can use this way.
<select v-model="userData.categoryId" class="input mb-3">
<option disabled value="null">Kategori</option>
<option
v-for="category in categoryList"
:key="category.id"
:value="category.id"
>
{{ category.name }}
</option>
</select>
export default {
data() {
return {
categoryList: [],
userData: {
title: null,
categoryId: null,
},
};
},
The important thing here is what the categoryId value is, the default option value should be that.
categoryId: null,
<option disabled value="null">Kategori</option>
Here we use categoryId as value in v-model and initialize it with null. Value must be null in default option.
<select v-model="userData.categoryId" class="input mb-3">