Select the drop-down option to categorize the list by date

Currently, I am in the process of integrating Vue.js into my project step by step, particularly for data binding purposes. To achieve this, I have included the Vue.js script in the footer and created a main.js file to house my Vue scripts.

One of the challenges I am facing is sorting a data list by date using a dropdown select option that provides date ranges. Despite searching online for tutorials, I have yet to find a solution that aligns with my requirements. Could someone offer guidance on how to accomplish this task?

<div id="date-range">
    <h3>Activity Overview</h3>
    <select id="selected" class="activity-overview__select" v-model="selected">
        <option value="24hr">Past 24 Hours</option>
        <option value="7days">Past 7 Days</option>
        <option value="14days">Past 14 Days</option>
    </select>
    <ul>
        <li>{{ selected.id }}{{ selected.text }}{{ selected.date }}</li>
    </ul>
</div>

var incidentCount = new Vue({
    el: '#incidentCountID',
    data: {
        incidentList: [
        { id: 0, text: 'Run', date: '2018-07-11' },
        { id: 1, text: 'Jump', date: '2018-07-10' },
        { id: 2, text: 'Skip', date: '2018-07-06' },
        { id: 3, text: 'Dance', date: '2018-07-05' },
        { id: 4, text: 'Swing', date: '2018-07-01' },
        { id: 5, text: 'Hop', date: '2018-05-29' },
        { id: 6, text: 'Bounce', date: '2018-06-29' },
        { id: 7, text: 'Crawl', date: '2018-06-27' },
        { id: 8, text: 'Walk', date: '2018-06-26' },
        { id: 9, text: 'Spin', date: '2018-06-25' },
        { id: 10, text: 'Skate', date: '2018-06-07' },
        { id: 11, text: 'Hike', date: '2018-06-05' }
      ]
    },
    methods: {
        ???
    }
});

Any assistance would be greatly appreciated!

Answer â„–1

Here is an example showcasing how it can be done. All it requires is a single computed property to sort data based on the selected date range. I've also modified some dates in your example to demonstrate how the filtering functionality operates.

(If you intend to handle dates, I suggest using the momentjs library, which simplifies working with dates (parsing, operations) significantly.)

var filterTypes = {
   Days: 0,
   Hours: 1
}

var incidentCount = new Vue({
    el: '#app',
    data: {
        incidentList: [
        { id: 0, text: 'Run', date: '2018-07-19' },
        { id: 1, text: 'Jump', date: '2018-07-17' },
        { id: 2, text: 'Skip', date: '2018-07-11' },
        { id: 3, text: 'Dance', date: '2018-07-06' },
        { id: 4, text: 'Swing', date: '2018-07-01' },
        { id: 5, text: 'Hop', date: '2018-05-29' },
        { id: 6, text: 'Bounce', date: '2018-06-29' },
        { id: 7, text: 'Crawl', date: '2018-06-27' },
        { id: 8, text: 'Walk', date: '2018-06-26' },
        { id: 9, text: 'Spin', date: '2018-06-25' },
        { id: 10, text: 'Skate', date: '2018-06-07' },
        { id: 11, text: 'Hike', date: '2018-06-05' }
      ],
      filters: [
        {
           value: 24,
           type: filterTypes.Hours,
           title: 'Past 24 Hours'
        },
        {
           value: 7,
           type: filterTypes.Days,
           title: 'Past 7 Days'
        },
        {
           value: 14,
           type: filterTypes.Days,
           title: 'Past 14 Days'
        }
      ],
      selectedFilter: ''
    },
    computed: {
        filteredList() {
            if (!this.selectedFilter) {
                return this.incidentList;
            }
            let multiplier, date;
            switch(this.selectedFilter.type) {
               // one hour milliseconds
               case filterTypes.Hours: 
                   multiplier = 60 * 60 * 1000; break;
               // one day milliseconds
               case filterTypes.Days: 
                   multiplier = 60 * 60 * 1000 * 24; break;
            }
            date =  Date.now() - this.selectedFilter.value * multiplier;
            return this.incidentList.filter((item) => Date.parse(item.date) >= date);
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<div id="date-range">
    <h3>Activity Overview</h3>
    <select class="activity-overview__select" v-model="selectedFilter">
        <option value="">All</option>
        <option v-for="f in filters" :value="f">{{ f.title }}</option>
    </select>
    <ul>
        <li v-for="incident in filteredList" :key="incident.id">
            {{ incident.id }} {{ incident.text }} {{ incident.date }}
        </li>
    </ul>
</div>
</div>

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

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

Retrieve the rowid from the first column of a jqGrid row

I want the first column of my jqGrid to display the rowid number number | name | class 1 | A | acceptable 2 | B | good 3 | C | bad Alternatively, I would like to add a column like this (image) https://docs.google.com/file/d/0Bxi6bFcYZ_MgYTI1dUJCMWEtd0E/ ...

Discover if every single image contains a specific class

HTML : <div class="regform"><input id="username" type="text" name="username" placeholder="Username" required><h3 class="check"><img src=''/></h3></div> <div class="regform"><input id="password" type=" ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

AngularJS: Controller causing an unchecked error

I'm a beginner to AngularJS and I'm struggling to understand why I'm not getting a response when clicking the button. Any help would be greatly appreciated. I've reviewed other examples of controllers being used but I can't seem to ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

Sleek carousel design with optimal spacing between images

Solving the Issue Utilizing Ken Wheeler's Slick plugin has allowed me to create a carousel on my website. However, I've encountered an issue where the images inside the <a> tag aren't evenly spaced and are even overlapping in some ins ...

Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" cla ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Transfer the address information to the billing address fields

I need assistance with copying the user's address to the billing address fields based on a checkbox value. Currently, when the checkbox is checked, only the last input field value is being copied over to the billing address section. It is crucial that ...

What is the proper way to attach the form tag action value in an EJS template?

Does anyone know about this? I am currently testing some JavaScript code: function mem_join_next() { if (document.mem_join.email.value == "") { alert("please input your email ID"); document.mem_join.email.focus(); return; } documen ...

Tips for making immutable state changes in React

Is there a way to update specific content in the state without affecting all other data stored in the state? Just to provide some context: The function below is executed within another "handleChange" function that takes the event as input and assigns the ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

How can Angular prevent displaying 404 errors in the console by utilizing fallback mechanisms?

I have implemented a custom directive that loads a backup image source if the initial one returns a 404 error. Here is the code for the directive: .directive('errSrc', function() { return { link: function(scope, element, attrs) { ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Only grant API access to my frontend application with a daily rotating API key

As I work on developing an API exclusively for my Vue.js application to display data such as movie times and video on demand links, I am wary of unauthorized access from other individuals or bots seeking free data. While I understand that fully restricting ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

What is the process of converting a value from an HTML form into a PHP variable?

I am looking to update the order preparation time. I have created an HTML form, but I am facing issues passing it into a PHP variable after this code block. I have tried using Cookies and POST method, but neither has helped me so far. <form> ...