Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that value to the onchange method so that choosed = item.id.

Here is the function in my 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 method to get device data from the DeviceController:

    getDevices() {
        axios.get(`/api/devices`)
          .then(response => {
              this.devices = response.data;
          });
    },

Here is the code for my select option:

<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>

My choosed v-model and devices JSON data, which the item.id value is retrieved from, are as follows:

 export default {
        data() {
            return {
                devices: {}, 
                choosed: null,
            }
        },

This is my onChange function in the method:

        onChange: function(){
            this.choosed = this.item.id;
        },

Answer №1

Give this a try.

<template>
  <div id="app">
    <select 
      class="form-select form-select-lg mb-3" 
      @change="onSelectionChange($event)"
    >
      <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>
    <p>Selected id: {{ selected }}</p>
  </div>
</template>

<script>

export default {
  name: "App",
  data() {
    return {
      selected: null,
      devices: [
        {
          id: 1,
          device_name: 'iphone'
        },
        {
          id: 2,
          device_name: 'android'
        }
      ],
    };
  },
  methods: {
    onSelectionChange: function (event) {
     this.selected = event;
    }
  }
};
</script>

Answer №2

Check out this new code snippet: https://codesandbox.io/s/vue-2-playground-forked-8yeqkx?file=/src/App.vue

<template>
  <div id="app">
    <select
      class="form-select form-select-lg mb-3"
      v-model="choosed"
    >
      <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>
    <p>Selected id: {{ choosed }}</p>
  </div>
</template>

<script>
const devices = async () => {
  await new Promise((r) => setTimeout(r, 2000));
  return [
    {
      id: 0,
      device_name: "Device A",
    },
    {
      id: 1,
      device_name: "Device B",
    },
    {
      id: 2,
      device_name: "Device C",
    },
  ];
};

export default {
  name: "App",
  data() {
    return {
      choosed: null,
      devices: [],
    };
  },
  async mounted() {
    this.$set(this, "devices", await devices());
  },
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of the 'this' context type void not being assignable to type rule?

Currently, I am conducting tests using Typescript to explore the feasibility of a project I have in mind. In one of my functions, I need to specify the type of 'this' as a class. While it technically works, I continue to encounter an error messag ...

Accepting insecure certificates in Chrome with Selenium-Webdriver in JavaScript: A Step-by-Step Guide

After generating a test script using Selenium-IDE in Javascript-Mocha format, I encountered an issue with an insecure certificate when trying to access a remote URL locally. To address the problem, I need to modify the generated TestScript to include Chro ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

Update a JSON value using an MUI Switch element

I am currently developing a feature that involves toggling the state of an MUI switch based on API responses. The status of the Switch is determined by the Active field in the API response. If the JSON field is 1, the switch is turned on, and if it's ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

Eliminate elements from an array within a promise

I am facing an issue with the currentBillCyclePath parameter in the following function. I need to use this parameter to filter out certain elements after executing the query. However, inside the while loop, the value of currentBillCyclePath is undefined. ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Javascript - Execute function after all nested forEach loops have finished running

I'm finding this task to be quite challenging, as I am struggling to comprehend it fully at the moment. The issue involves nested forEach loops, and I require a callback function to execute once all the loops have finished running. I am considering u ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Utilizing query parameters in Next.js

I've been working on a unique Next.js application that incorporates both infinite scroll and a search input feature. The infinite scroll functionality loads 6 additional items whenever the user reaches the bottom of the page. On the other hand, the s ...

Does Vetur have additional undefined types in the type inference of deconstructed props?

When reviewing the code below, Vetur concluded that x,y are of type number | undefined. The presence of undefined is leading to numerous warnings when using x,y further in the code. Is there a way to eliminate the undefined from the type inference? <s ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value. Below is the relevant code snippet: $scope.getSubTotalSCTax = function(){ TableService.checkOut('SubTo ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

Sending information from JavaScript to Python scripts: best practices

Within this HTML file, I have included a script where an ajax request is being made to pass a specific string to a Python function. var message = "hello there!!!" $.ajax({ url: "../SCRIPTS/cond.py", type: 'POST', ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Combine all the HTML, JavaScript, and CSS files into a single index.html file

So here's the situation - I am utilizing a C# console application to convert four XML files into an HTML document. This particular document will be circulated among a specific group of individuals and is not intended to be hosted or used as a web app; ...

Tips for reducing code length in jQuery

Here's an interesting question that I've been pondering. Is there a more efficient way to optimize and condense code like the one below? Could it be achieved using functions or loops instead of having lengthy jQuery code? var panels = ["panel1", ...

Updating choices within a div in real-time by changing the select box dynamically

I need to swap out the select box that is nested inside this div <div class="models"> <select disabled="disable"> <option>Model Name</option> </select> </div> I am attempting to target the div and manipul ...