How to Set Default Value in Dropdownlist in Vue.js - javascript

How do I set the first option as a default value in dropdownlist?
<select :disabled=true class="custom-select" v-model="Status">
<option disabled value>Select Any</option>
<option v-for="status in statusList" v-bind:value="{StatusId:status.StatusId,StatusName:status.StatusName}" :key="status.StatusId">{{ status.StatusName }}</option>
</select>
Here v-model="Status" is an object. So, when I have set it like below It's not working:
data() {
return {
Status: 1
};
},
Here, 1 is the id of first option.

Status needs to be an object as well if you want it to match.
data() {
return {
Status: { StatusId: 1, StatusName: 'name' }
}
}
All of the properties of your default Status will need to match one of the options in order for it to be selected.
But note that there is probably no good reason here to use this pattern of setting the option value to an object. Better to set it to the StatusId, and use that selected id or a computed to process the option wherever you need to use it.

Related

v if equal to data attribute

how do you do this? I have a method that gets called on a select where on change I want to hide everything else thats not the selected attribute. When the see all option is picked, everything should be shown.
The thought process is to leverage v-model to check if its equal to a data attribute and hide everything else otherwise. If all options are selected, the v-model (in this case, "selectedDep") equals out to just nothing, show them all.
Vue.js v-if for attributes
is only talking about adding the attr which is not my problem.
I'm trying to do something like this:
Select Tag:
<select type="text" id="job-teams" #change="onDepChange($event)" placeholder="Filter By Department" name="teams" v-model="selectedDep">
<option value="">All Departments</option>
<option v-for="listing in listings" :value="listing.title">{{ listing.title }}</option>
</select>
Div I want to hide based on selected option (this is where I'm stuck)
<div v-for="listing in listings" :data-department="listing.title" v-if="selectedDep === '' || selectedDep === data-department">
Data
data: {
listings: [],
locations: [],
message: 'job postings',
selectedDep: '',
error: null
},
Method
onDepChange: function(event) {
this.selectedDep = event.target.value
console.log(this.selectedDep)
}
the first attempt looks like this:
<div v-for="listing in listings" :data-department="listing.title" v-if="selectedDep === '' || selectedDep === data-department">
This throws multiples of the same error in the console:
Property or method "department" is not defined on the instance but
referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by
initializing the property. See:
https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
Where is it getting "department"? I don't have "department" but "data-department"? I read the documentation:
Since Vue doesn’t allow dynamically adding root-level reactive
properties, you have to initialize Vue instances by declaring all
root-level reactive data properties upfront, even with an empty value:
If you reference my data object above I'm doing that. The link/documentation is not helpful.
The second attempt:
<div v-for="listing in listings" :data-department="listing.title" v-if="selectedDep === '' || selectedDep === :data-department">
I thought maybe adding a colon would do it but
[Vue warn]: Failed to generate render function:
SyntaxError: Unexpected token ':' in
Is apparently a syntax error so that doesn't work.
v-show based on select option data attribute value
This answer only seems to address boolean values (true/false) not comparing several data attribute values.
To conclude
In the context of vue js, how do you do: "if the selected item in a dropdown matches the data attribute of a div - show that one and hide everything else, otherwise if its empty show them all" ... ?
You don't need a v-if for controlling what data you want to display. Also, you shouldn't use v-if on the same tag as with v-for (more on this here).
Solution: create a computed value and list that with a v-for.
new Vue({
el: "#app",
data: {
listings: [{
title: "Listing 1",
},
{
title: "Listing 2",
},
{
title: "Listing 3",
},
],
locations: [],
message: 'job postings',
selectedDep: '',
error: null
},
computed: {
selectedListing() {
return this.selectedDep ? this.listings.filter(({
title
}) => title === this.selectedDep) : this.listings
},
},
methods: {
onDepChange: function(event) {
this.selectedDep = event.target.value
console.log(this.selectedDep)
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select type="text" id="job-teams" #change="onDepChange($event)" placeholder="Filter By Department" name="teams" v-model="selectedDep">
<option value="">All Departments</option>
<option v-for="listing in listings" :value="listing.title">{{ listing.title }}</option>
</select>
<div v-for="listing in selectedListing" :department="listing.title">
{{ listing.title }}
</div>
</div>
Ok I figured it out: vue,js doesn't like comparing something to data-department (I don't know why, if anyone reading wants to leave a comment explaining why, much appreciated) you instead have to compare to the object value (in this case, listing.title)
So:
<div v-for="listing in listings" v-if="selectedDep === '' || selectedDep === listing.title">

get select value from a drop with angulars reads error

I'm trying to get the selected value from a drop down list with angularjs. When I select the value I get this error angular.min.js:108 TypeError: Cannot read property 'ftype' of undefined
HTML
<select name="select" ng-model="queryBy" ng-change="get_search_value(item)">
<option ng-repeat="item in filter" value="{{item.ftype}}">{{item.ftype}}</option>
</select>
JS
$scope.search_type='';
$scope.filter = [
{ id: 1, ftype: "Complaint Type"},
{ id: 2, ftype: "Region" },
{ id: 3, ftype: "District"},
];
$scope.get_search_value=function(item){
$scope.search_type=item.ftype;
alert(item.ftype)
}
My guess is item is invisible on the level of <select>. Whatever is in the <option>(so, the 'item') should be saved in the ng-model value, which is queryBy. Why are you passing item to the get_search_value? Try acessing the queryBy in the get_search_value function instead
I think you've misunderstood AngularJS... It does all of this for you. You don't need to update a separate value and you don't need a change event to do this for you.
Here is what I think you're trying to achieve:
HTML
<select name="select" ng-model="queryBy">
<option ng-repeat="item in filter" value="{{item.ftype}}">{{item.ftype}}</option>
</select>
JavaScript
$scope.filter = [
{ id: 1, ftype: "Complaint Type"},
{ id: 2, ftype: "Region" },
{ id: 3, ftype: "District"}
];
// you can access the selected value by using $scope.queryBy
That's right, just using $scope.queryBy (or just queryBy in your HTML) will give you the value of the selected option. As tymeJV mentioned, you can also use ngOptions instead of ngRepeat for your options. I'd also recommend looking into using ngBind instead of curly braces where you can, it will avoid the expression itself flashing before being evaluated.
You should be using ngOptions - your item is inaccessible the way you currently have it. Here's a quick refactor that should work:

Vuejs Passing data to select element from ajax request not reactive

I am trying to make dynamic select input that populates it's option elements depending on the the response of ajax with the following code. Everything is working fine if the data is hardcoded however when I try to make option dynamic based on the response I don't get reactivity.
In short let's say I have an object {Foo: 'Bar', Lorem: 'Ipsum'} I get
<select>
<option value="Foo">Bar</option>
<option value="Lorem">Ipsum</option>
</select>
My problem is when I want to make the data dynamic using the function below I still get the same option even though I now have {Enet: 'Dolor', Magna: 'Aliqua', mollit: 'Anim'} Is there a better approach to this? Or Am I missing Something.
Function responsible for populating the object:
$.get('/registrar/levels', function (data) {
for (const datum of data) {
addModal.levelFields[datum.name] = datum.id;
}
});
The component:
Vue.component("modal-add-form", {
props: {
formName: String,
formType: [String, Number],
options: Object,
},
template: `<div class="form-group" v-if="formType !== 'select'">
<label :for="formName" v-text="formName"></label>
<input :type="formType" class="form-control" :name="formName" :id="formName" value="" :placeholder="formName">
</div>
<div v-else>
<select :name="formName" class="form-control">
<option v-for="(value, name) in options" :value="value" v-text="name"></option>
</select>
</div>`
});
You shouldn't directly reassign data value because Vue cannot detect property additions and rerender view. You should do it via Vue.set or this.$set like this:
$.get('/registrar/levels', (data) => {
for (const datum of data) {
this.$set(this.addModal.levelFields, datum.name, datum.id)
// addModal.levelFields[datum.name] = datum.id;
}
});

How to use ng-options to set default value of select element reading from object?

I have the following data:
$scope.users = [
{
'id': 0,
'name': 'Tom'
},
{
'id': 1,
'name': 'Jack'
}
];
And I have a default object that is dynamically generated.
$scope.default = {
'id': 1,
'name': 'Jack'
}
I'm trying to set a default selected option in my ng-options based on $scope.default but because it's an object as opposed to a string, it doesn't seem to work.
<select ng-options="user.name for user in users" ng-model="default.name"></select>
I'm aware of this other question, but it doesn't work with objects.
how to use ng-option to set default value of select element
You can to use "as" and "track by" to define the label and the field to be compared:
<select ng-options="user as user.name for user in users track by user.id" ng-model="default"></select>
see the jsbin
Check out https://docs.angularjs.org/api/ng/directive/ngInit
or try:
If it's dynamic ordering, then you could track by a custom field, user.orderNum or something you can alter. I haven't tested, but should get you in the right direction.
By default, ngModel watches the model by reference, not value. Try
<select ng-options="user.name for user in users track by user.name " ng-model="default.name"></select>.
More here

angularjs filter Dropdown options by object properties

I can't seem to find the way to filter my options in my drop down.
<div>
<select>
<option ng-repeat="draw in draws| filter:{draw.perform == true && automatic == false}">
</option>
</select>
</div>
data looks like :
{
automatic: true,
date: 1417388400000,
drawQuantity: 0,
number: 1,
offer: {
image: "/"test,
number: 1
},
perform: true
}
I get the data from firebase, that's why i need to do filtering on frontend. If anyone was wondering.
Your syntax is incorrect. Try this instead:
ng-repeat="draw in draws| filter:{perform: true, automatic: false}"
If you need to filter by property values you should use object notation.

Categories

Resources