How can I update information based on the chosen option in a select dropdown using Vue?

I have a chart displayed in my user interface that needs to be updated based on the selected time period. By default, the chart displays data from the past year, but when the user selects "Month," it should show data from the past month.

    <div class="graph">
      <p>Select {{ selected }}</p>
         <form>
           <select class="select" v-model="selected">
             <option value="year">Year</option>
               <option value="month">Month</option>
                 <option value="week">Week</option>
           </select>
         </form>
   <canvas id="mix" count="2"></canvas>
   <chartjs-line target="mix"></chartjs-line>
   <chartjs-bar :labels="mylabels" :datasets="mydatasets" target="mix"></chartjs-bar>
   </div>
export default { 
  data(){
   return{
     mydatasets:[{
                    responsive:true,
                    borderWidth: 2,
                    data: [20, 50, 20, 41, 26, 15, 20, 10, 29, 5, 33, 55] // this data should update based on the selected time period
                }]
         }
        }
      }

Answer №1

In order to display specific data based on the selected value in the drop-down menu

    <form>
       <select class="select" @change="changeHandler" v-model="selected"> // event listener for change
         <option v-bind:key="item" v-for="item in selectArr">{{item}}</option>
       </select>
    </form>
   export default {
      data(){
         selected: 'Year',
         selectArr: ['Year', 'Month', 'Week']
      }
   },
      methods:{
      changeHandler(){
         let selected = this.selected;
         if (selected === 'Month'){
            this.dataChart = [2, 12, 8, 22, 31, 6, 10, 32, 5, 36, 21, 21];
         } else if (selected === 'Week') {
            this.dataChart = [8, 2, 18, 3, 13, 32, 10, 8, 12, 34, 21, 12];
         } else if (selected === 'Year') {
            this.dataChart = [44, 49, 48, 49, 55, 47, 43, 55, 53, 43, 44, 51];
          }
      }
   }

Answer №2

Observing the transformation of the "selected" through the watch property...

<script>
export default { 
  data(){
    return{
      mydatasets:[{
        responsive:true,
        borderWidth: 2,
        data: [20, 50, 20, 41, 26, 15, 20, 10, 29, 5, 33, 55] // this data needs to be updated based on selected value
      }]
    }
  },
  watch: {
    selected: {
      immediate: true,
      handler: function (newValue) {
        switch (newValue) {
          case "Year":
            // update this.mydatasets[0].data with something
            break;
          case "Month":
            // update this.mydatasets[0].data with something
            break;
          case "Day":
            // update this.mydatasets[0].data with something
            break;
        }
      }
    }
  }
}
</script>

Answer №3

To achieve this functionality, you can utilize the PHP switch case along with JavaScript or AJAX. Below is an illustrative example using PHP:

<?php
    $selectedPage = null;
    if(isset($_POST['page'])){
        $selectedPage = $_POST['page'];
    }
    switch($selectedPage){
        case 'page3': include_once('/path/to/some.php'); break;
        case 'page2': include_once('/path/to/some.php'); break;
        case 'page1': include_once('/path/to/some.php'); break;
        default: include_once('/path/to/default.php'); break;
    }
    ?>

<form action="" method="post">
    <select name="page" onchange="window.location=this.value"">
        <option value="page1"<?php if($selectedPage == "page1"){ echo " selected"; }?>>Year</option>
        <option value="page2"<?php if($selectedPage == "page2"){ echo " selected"; }?>>Month</option>
        <option value="page3"<?php if($selectedPage == "page3"){ echo " selected"; }?>>Week</option>
    </select>
</form>

The behavior depends on the option clicked. For instance, selecting "Year" sets $selectedPage to 'page1', which triggers the display of the year-related chart in some.php file.

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

I'm just getting started: an image carousel featuring a unique twist with random quote overlays, but there's a catch - it only activates on the very first image... what comes next?

After successfully displaying the generator over the first image, I encounter a problem with the second and third images where it seems to disappear. However, upon cycling back to the first slide, the generator reappears with a different quote. I've a ...

How to make a JQuery list item unselectable when appending it

I encountered a strange issue while using jQuery to append items to a list. <ul id="idNicheItems" class="clScrollItems ui-widget-content ui-corner-all"> <li id="NicheItem_1"> Item 1</li> <li id="NicheItem_2"> Item 2</li& ...

Ways to ensure that ng-view stays idle until an XHR response is received

Is there a way to make the ng-view wait for an xhr request? I have two controllers set up for a routed ng-view - the first one loads perfectly, but the second one doesn't render properly because the xhr response is happening after partial.html has bee ...

Duplication of CSRF Tokens within Vue Router on Laravel 5.3 with Vue 2 JavaScript

I am facing an issue with the session token generation. When I send the token via AJAX or AXIOS (since I am using Vue and Vue Router for API fetching), it results in a mismatch. The response I receive when posting data shows that the AJAX token does not ...

The result of combining two JavaScript variables

When I multiply a variable by 2 and assign the value to another variable, why do I get 0? My goal is to toggle the visibility of blocks every time a button is pressed. Oddly enough, it works when I use count++ * 2. For code reference, please refer below: ...

Why is my NextJs app loading slowly on Safari but quickly on Chrome?

Currently, I am in the process of developing a web app using nextjs. I have encountered some issues with linking to pages, particularly the home page which contains multiple svgs and images. The performance lags when using Safari, as it does not show a loa ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

`The process of adding an element to the beginning of an array``

I find myself in this scenario: I am dealing with 2 array1 variables, defined as array1 = ["fruit","vegetables"]; and array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"]) T ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Using Vue.js to dynamically style components in a v-for loop using Vuex data

Having trouble with this task... I have a table displaying rows of data fetched through vuex. The styling updates correctly, but it's not reflecting in the browser until I refresh or recreate the component. I'm stuck on finding the best way to im ...

Formulation, on the other side of the comma

I have a calculation script that is almost working perfectly, but it seems to be ignoring values with decimal points. Can anyone offer some guidance on how to fix this issue? var selects = $('select'); var inputs = $('input'); selects. ...

What is the process for updating my API data with information submitted through a form?

I am encountering a challenge with my Products component that fetches data from an API endpoint. I also have a Form component where users can input data to update the Products component, displaying both fetched and new data. How can I achieve this? I passe ...

Tips for adjusting the height of MUI Date Picker to fit your preferences

<Box sx={{ m: 1 }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker label="Enter Date" slotProps={{ textField: { height: "10px" } }} ...

Executing an Amplifyjs GET request containing a request body

Is it possible to utilize GET requests with a message body using AmplifyJS? Specifically, I am curious about the process of achieving this functionality with AmplifyJS. While synthetic tests function properly (using Fiddler as my test client), I have enc ...

Ensure to preselect the radio button based on the Day's value

I have set up my Radio buttons with corresponding content to be displayed when clicked. I want to automatically pre-select the tab button based on the current day. For example, if today is Sunday, the page should load showing the contents for Sunday. If i ...

Hide the div when hovering occurs

I need a way to hide the 'sample' div when hovering over it and then show it again when the mouse moves away $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu&a ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

Utilizing Azure SDK to send an email

In my Node.js project, I am currently utilizing azure-graph: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId, { tokenAudience: 'graph' } ...