get selected object from options loop

v-select options
vue select options
vue for loop
vuejs loop options
vue js select option
vuex select option
selected item vue
v-select array of objects

I'm trying to find a way to bind array of objects within Vue select-element. The case is somewhat as follows:

data: {
  ideas: [
    { id: 1, code: "01A", text: "option 1", props: [] }, 
    { id: 2, code: "02A", text: "option 2 , props: [{ details: "something" }]}
  ]},
  currentForm: {
    something: "foo",
    else: "bar",
    ideaCode: "01A",
    text: "option 1"
  }
];

... and in HTML ...

<select v-model="currentForm.ideaCode" @change="setCodeAndLabelForForm(???)">
  <option v-for="i in ideas" value="i">{{ i.text }}<option>
</select>

Basically I need to be able to track which object user selects, trigger my own change-event, all the while having binding with a single key from another object... selected value / reference-key should be separated from user-selected option/object. Note: currentForm is not same object-type as option! It only contains some of those properties which option happens to have, and which I'm trying to transfer to options by triggering change-event for user-selection.

The problem is I haven't figured out how to pass currently selected value for the function OR how to write something like:

<select v-model="selectedIdea" @change="setCodeAndLabelForForm" :track-by="currentForm.ideaCode">
  <option v-for="i in ideas" value="i">{{ i.text }}<option>
</select>

One possible (and working) approach is:

<select v-model="currentForm.ideaCode" @change="setCodeAndLabelForForm">
  <option v-for="i in ideas" value="i.ideaCode">{{ i.text }}<option>
</select>

setCodeAndLabelForForm: function() {
    var me = this;
    this.ideas.forEach(function(i) {
        if(i.ideaCode == me.currentForm.ideaCode) {
            me.currentForm.ideaCode = i.selectedIdea.ideaCode;
            me.currentForm.text = i.text;
            ... do stuff & run callbacks ...
        }
    });
}

... but it just seems terrible. Any better suggestions?

You can implement like this:

Create empty object data to track the selected value:

currentForm: {}

Watch currentForm on the model and pass the selected object:

<select v-model="currentForm" @change="setCodeAndLabelForForm(currentForm)">

Pass in the selected value in option: (you were doing right in this step, but I just changed i to idea as it's little confusing looping index)

<option v-for="idea in ideas" :value="idea">{{ idea.text }}<option>

Apply your method:

setCodeAndLabelForForm(selected) {
  // Now, you have the user selected object
}

Get Value or Selected Option in Select Box Using JavaScript, The text property of an option is the content of the option element. Using a for Loop to Obtain Selected Option. You can use a for loop to iterate through the options  There are a variety of ways to use JavaScript to obtain the value of the selected option in a select list or a reference to the selected option: Use the value property of the select list. Use the selectedIndex property. Loop through the options and determine which one is selected and return either its value or a reference.

I don't know if this is the best solution, but I solve this problem using computed properties like this:

In the JavaScript file (ES6):

data () {
    return {
        options: [
            { id: 1, text: "option 1" },
            { id: 2, text: "option 2" }
        ],
        selectedOptionId: 1
    }
},
computed: {
    selectedOption () {
        return _.find(this.options, (option) => {
            return option.id === this.selectedOptionId
        });
    }
}

In the HTML file:

<select v-model="selectedOptionId">
  <option v-for="option in options" :value="option.id" :key="option.id">{{ option.text }}<option>
</select>

The '_' symbol is a common JavaScript library called Lodash and I highly recommend the usage. It can make you save some precious time.

Vuex nested loop, how to handle v-model on select/option, Vuex nested loop, how to handle v-model on select/option Consider using an array of objects and use v-model on an object property instead. Core Level 2 Document Object: Return Value: An HTMLOptionsCollection Object, representing all <option> elements in the <select> element. The elements in the collection are sorted as they appear in the source code

If you know your options will only come from that v-for="i in ideas" then the <option> indexes will be the same as the item indexes.

Thus <select>.selectedIndex will be the index of the selected this.item.

new Vue({
  el: '#app',
  data: {
    ideas: [
      { id: 1, code: "01A", text: "option 1", props: [] }, 
      { id: 2, code: "02A", text: "option 2" , props: [{ details: "something" }]}
    ],
    currentForm: {ideaCode: "01A", text: "option 1"}
  },
  methods: {
    setCodeAndLabelForForm: function(selectedIndex) {
      var selectedIdea = this.ideas[selectedIndex];
      this.currentForm = {ideaCode: selectedIdea.code, text: selectedIdea.text};
    }
  }
})
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>

<div id="app">
  <select v-model="currentForm.ideaCode" @change="setCodeAndLabelForForm($event.target.selectedIndex)">
    <option v-for="i in ideas" :value="i.code">{{ i.text }}</option>
  </select>
  <br> currentForm: {{ currentForm }}
</div>

jQuery Loop Select Options, jQuery code snippet to loop select box options (drop down boxes) in a form to get the values and text for each option, manipulating values in  jQuery Loop Select Options. Simple jQuery code snippet to loop select box options (drop down boxes) in a form to get the values and text from each option. Useful for manipulating values in form select boxes.

A little bit better workaround: use index in v-for

<select v-model="selIdeaIndex" @change="setCodeAndLabelForForm">
  <option v-for="(i,idx) in ideas" value="idx">{{ i.text }}<option>
</select>

For the js:

data: {
  selIdeaIndex:null,
  ideas: [
    { id: 1, code: "01A", text: "option 1", props: [] }, 
    { id: 2, code: "02A", text: "option 2 , props: [{ details: "something" }]}
  ]
},
methods:{
    setCodeAndLabelForForm: function() {
        var selIdea = this.ideas(this.selIdeaIndex);
        //Do whatever you wanna do with this selIdea.
    }
}

Retrieving selections, It is possible to extend the <option> elements representing the current selection(s​) with HTML data-* attributes to contain arbitrary data from the source data objects  Right-click in the drawing area, and choose Options. On the Selection tab, choose the settings you want. Among other settings, you can set Whether objects to be selected are previewed during selection.

A humble way is using $ref.

There is a solution using $ref and @change.

Vue.js get selected options' raw object

e-World 7, All the objects enclosed in the loop get selected. You can press the Alt key and then click to switch between the two zoom options if the zoom tool is selected. The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array. To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter.

Getting and Setting, When the options array contains objects, vue-select returns the whole object as dropdown value upon selection. This approach makes no assumptions about the​  Standard Aliases for Select-Object: select Select-Object will create new objects by copying the values of the selected properties from the input objects. If the input object is an array, the -First, -Last and -Unique parameters may be used to select particular objects, for more powerful object filtering, use Where-Object .

:selected Selector, Example: Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the  My doubt is all about how to get corresponding selected values by passing the object as selectedValue from the controller or by using model (item.Data.CategoryID) in the view page ,which will provide the drop down list in the foreachloop corresponding selected value.

The product_option object · Shopify Help Center, Returns the currently selected value for this product option. Input. <select> {% for value in product_option.values  In Angular select element, the value attribute of <option> element can bind an object using property binding and one field of the object can be used to display items. For validation of select element, we need to use validation attribute such as required .

Comments
  • Unless there is a way to separate way to separate referencing key and v-model, I may need to fallback to tracking only ideaCode -value with v-model and separate object-parsing to @change -event, meaning that I would need to parse that object-array manually within function (filter/map/forEach -solution)... but I would prefer to simply point user-selected object from with template syntax.
  • Sorry for misleading you. CurrentForm isn't actually the selected option, but an object which happens to contain those two fields which need to be copied from selected option... currentForm could have ~20 other properties unrelated to "idea" and from your suggestion I believe currentForm would be overwritten by selection... not what I was looking for, but thanks for suggestion.
  • currentForm will hold only one object not whole. just try it and you'll know it is an easier solution.
  • and in your method, you can take property whatever you want... like: selected.code
  • Interesting approach. Very close to my fallback-solution, but I'm bit worried how computed vs change-event would balance out. I'm looking for clear user-triggered input (selection/change), which should handle change-action for selected option only once when change is triggered.
  • If you debug it with a breakpoint inside the selectedOption function, you'll see it is triggered only when this.selectedOptionId changes. I guess Vue only recalculates the computed properties when they should be.
  • Quite close to my fallback-suggestion, except that my option wouldn't rely on index and would thus probably be safer as it validates acceptable option within forEach-loop... but I still find my option poor solution in comparison to what I'm looking for (directly from template). Thanks for giving it a thought none-the-less! BTW: I did try similar approach by passing $event.target.data , but apparently I got only [object object] -string instead of actual object, and I still had trouble separating model vs referring key (which should contain the selected value and/or referral)
  • You get [object Object] because it converts to string when passing data attributes. Other than the solution I gave here, you could filter the collection, like you did (though I'd use var selectedIdea = this.ideas.find(i => i.code === this.currentForm.ideaCode); and the rest like my code - without having to pass $event as arg). Using a regular <select>, that's it. If that does not suffice to you, I recommend using a custom component (a v-select of vuetify, or one of the many standalone ones you will find on the internet), it will make this whole set/get value situation much smoother.