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];
});
},
}
}
Related
I have a problem when I visit the message page and I select a device, the v-model selected value will change. But if I visit the device page and contact page the v-model selected value will not change or become set to the last time value that I selected.
Here is my function in DeviceController to fetch devices:
public function devices()
{
try {
$devices = Device::orderby('id', 'asc')->get();
return response()->json($devices);
} catch (\Throwable $th) {
return response()->json(['message' => $th->getMessage()]);
}
}
Here is the function from method to get devices{} data from DeviceController:
getDevices() {
axios.get(`/api/devices`)
.then(response => {
this.devices = response.data;
});
},
Here is my select option code:
<select class="form-select form-select-lg mb-3" v-model="choosed" #change="onChange()">
<option :value="null">Choose Device to Send SMS</option>
<option v-for="item in devices" :key="item.id" :value="item.id" >{{ item.device_name }}
</option>
</select>
Here is my selected v-model and devices JSON which devices that item.id came from in data:
export default {
data() {
return {
devices: {},
choosed: null,
}
},
}
Here is my onChange function in method:
onChange: function(){
this.choosed = this.item.id;
},
Remove the function onChange - it is plain wrong.
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>
I'm using Vue 2 for a small blog project. I have a separate component for post's form and one of the form inputs is a select (for post's category). The select gets populated after the categories are fetched from DB. The component also gets a post object from parent component, that is also fetched from the db (see props: ['post']).
Here's the code:
// HTML
...
<select class="form-control" v-model="post.category_id">
<option
v-for="cat in categories"
v-bind:value="cat.id">
{{ cat.name }}
</option>
</select>
...
// JS
module.exports = {
props: ['post', 'url'],
name: 'postForm',
created: function() {
this.syncCats()
},
methods: {
syncCats: function() {
this.$http.get("/api/categories")
.then(function(res) {
this.categories = res.data
})
}
},
data: function() {
return {
categories: {}
}
}
}
The problem I'm having is that none of the options is selected by default. It looks like this. But when I open the select I see both categories from my db like this.
I want to select the correct (post.category_id == cat.id) value by default. How would I do this?
I've tried <select ... :v-bind:selected="post.category_id == cat.id"> but same happened.
Edit
Okay so now I've tried dumping both post.category_id and cat.id like this:
<div class="form-group">
<label>Category</label>
<select class="form-control" v-model="post.category_id">
<option
v-for="cat in categories"
:value="cat.id"
:selected="cat.id == post.category_id">
{{ cat.name }} {{ cat.id }} {{ post.category_id }}
</option>
</select>
</div>
And the result before I select any option is this - only cat.id gets printed, post.category_id does not. However after I select some option I post.category_id appears as well, like this. Notice how the "1" at the end only appears in 2nd screenshot, after I've selected one of the options, which is the {{ post.category_id }}.
This implies that the post is loaded after the categories and that I should somehow reinitialize the select after it's loaded. How would I do this? For reference this is the parent component that fetches the post.
<template>
<span id="home">
<postForm :post="post" :url="url"></postForm>
</span>
</template>
<script>
var postForm = require('../forms/post.vue')
module.exports = {
name: 'postEdit',
created: function() {
this.$http.get('api/posts/slug/' + this.$route.params.slug)
.then(function(response) {
if(response.status == 200) {
this.post = response.data
this.url = "/api/posts/slug/" + response.data.slug
}
})
},
data: function() {
return {
post: {},
url: ""
}
},
components: {
postForm
}
}
</script>
You'll need to set the selected attribute on the appropriate <option> and adhere to Vue's one-way data flow paradigm.
You can even add some extra usability sugar by disabling the <select> until both the post and categories are loaded...
<select class="form-control"
:disabled="!(post.category_id && categories.length)"
#input="setCategoryId($event.target.value)">
<option v-for="cat in categories"
:value="cat.id"
:selected="cat.id == post.category_id">
{{cat.name}}
</option>
</select>
and
methods: {
setCategoryId(categoryId) {
this.$emit('input', parseInt(categoryId))
}
}
Then, in the Vue instance / component that includes the above one, simply use
<post-form :post="post" :url="url"
v-model="post.category_id"></post-form>
See Components - Form Input Components using Custom Events for more information.
JSFiddle demo ~ https://jsfiddle.net/1oqjojjx/267/
FYI, I'd also initialise categories to an array, not an object...
data () {
return {
categories: []
}
}
You should be able to do something like following:
methods: {
syncCats: function() {
this.$http.get("/api/categories")
.then(function(res) {
this.categories = res.data
if(!this.post.category_id) {
this.post.category_id = this.categories[0].id
}
})
}
},
I'm using Vue.js with the Mininmalect HTML select plugin to display a list of countries by name and value (value being the 2 digit country code).
I've got it to work when using the plugin to select a country. It's adds the value to the selected state.
What I can't work out is how display a value/country when there is already one in state (i.e. from the database when the page loads).
This is what I have:
<template>
<select name="country" v-model="country">
<option v-for="country in countries" value="{{ country.value }}">{{ country.label }}</option>
</select>
</template>
<script>
export default {
data() {
return {
selected: 'GB',
countries: require('../utilities/countries.js'),
}
},
ready() {
var vm = this;
$('select').minimalect({
onchange: function(value) {
vm.selected = value;
}
});
}
};
</script>
I'm struggling to get the select attribute to appear, i.e. <option value="GB" selected>United Kingdom</option> so there is a default when the page is loaded.
You've got v-model="country", so if you just set the value of country to the database value, the select will automatically be set to that value.
data() {
return {
country: 'GB',
countries: require('../utilities/countries.js'),
}
},
ready() {
var vm = this;
$('select').minimalect({
onchange: function(value) {
vm.country = value;
},
afterinit: function() {
$('select').val(vm.country).change();
}
});
}
Change your v-model with selected. And I think your problem is a performance problem. Add a setTimeout for your function.
<template>
<select name="country" v-model="selected">
<option v-for="country in countries" value="{{ country.value }}">{{ country.label }}</option>
</select>
</template>
<script>
export default {
data() {
return {
selected: 'GB',
countries: require('../utilities/countries.js'),
}
},
ready() {
var vm = this;
setTimeout(function(){
$('select').minimalect({
onchange: function(value) {
vm.selected = value;
}
});
});
}
};
</script>
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">