"Dynamically setting the selected value in a drop-down box to the

Is there a way to dynamically set the value of a select box using JavaScript to show the current date and a selected period in the past? For example, if today's date is 2018-01-09 and I want to show the date from 30 days ago as selected 2017-12-10, then the option value should be 2018-01-03,2018-01-09. This same functionality should work for intervals of 7, 14, 30, 90, and 365 days. Here is what I have attempted so far...

setTimeout(function () {
  var today = new Date()
  var last7 = new Date().setDate(today.getDate()-7)
  var last14 = new Date().setDate(today.getDate()-14)
  var last30 = new Date().setDate(today.getDate()-30)
  var last90 = new Date().setDate(today.getDate()-90)
  var last365 = new Date().setDate(today.getDate()-365)

  $('#DateSelector').val('30').trigger("change");
}, 1000);

However, I am struggling to figure out how to use these variables in the option value.

<select name="DateSelector" id="DateSelector" onchange="overviewDates();">
   <option value="">Last 7 Days</option>
   <option value="">Last 14 Days</option>
   <option value="">Last 30 Days</option>
   <option value="">Last 90 Days</option>
   <option value="">Last 365 Days</option>
</select>

Answer №1

Instead of using setTimeout, it is better to call the function once the element is visible on the page. One way to achieve this is by utilizing the window's load event, although there are other methods available.

The setDate function returns a time value, but what you actually need is a formatted date string. Therefore, you will have to amend that aspect of your code. Subsequently, you must assign the updated values to the option elements in this manner:

// Update select values
function updateSelectValues(id) {
  var sel = document.getElementById(id);
  if (!sel) return;
  // Array of intervals to update
  Array.from(sel.options).forEach(function(opt) {
    var d = new Date();
    d.setDate(d.getDate() - opt.value);
    opt.value = formatDateYMD(d);
  });
}

// Function to format the date
function formatDateYMD(date) {
  return date.getFullYear() + '-' + 
    ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
    ('0' + date.getDate()).slice(-2);
}

// Trigger the updater
window.onload = function(){updateSelectValues('DateSelector')};
<select name="DateSelector" id="DateSelector" onchange="console.log(this.value)">
   <option value="7" selected>Last 7 Days</option>
   <option value="14">Last 14 Days</option>
   <option value="30">Last 30 Days</option>
   <option value="90">Last 90 Days</option>
   <option value="365">Last 365 Days</option>
</select>

Remember to designate one of the options as selected, usually the first one.

Answer №2

First, add the selected value to a variable and then call a function to subtract it from the current date.

function calculateDateDifference(e) {
 var s = e.target,
     selectedValue = s.options[s.selectedIndex].value,
     currentDate = new Date(),
     previousDate = currentDate.setDate(currentDate.getDate() - selectedValue);
     
     t.innerHTML = `The date ${selectedValue} days ago was: ${currentDate.toLocaleString()}`
 }
 
 var selectElement = document.getElementById("DateSelector").addEventListener("click", calculateDateDifference);
<select name="DateSelector" id="DateSelector">
   <option value="7">Last 7 Days</option>
   <option value="14">Last 14 Days</option>
   <option value="30">Last 30 Days</option>
   <option value="90">Last 90 Days</option>
   <option value="365">Last 365 Days</option>
</select>

<h1 id="t"></h1>

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

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Incorporating traditional Bootstrap styling directly into a React application without relying on the react-bootstrap library

My goal is to incorporate my existing bootstrap components into a React project without having to rewrite them to work with the react-bootstrap library. While I have successfully integrated the bootstrap CSS, I am facing issues with the functionality aspec ...

"Unlocking the Power of Facebook with Javascript and Ajax

My Cordova app successfully authenticates with Facebook, but when trying to retrieve data, I encounter errors. I suspect there may be an issue with my URL. Can anyone identify a mistake in this? Errors: app: makeAPICalls: error:setting authenticatedUser ...

Ways to refresh the information in local storage when new data has been chosen

I am in the process of developing an online ordering system where users can select items and add them to their shopping carts. To store the selected items, I am utilizing local storage so that they can be retrieved on the next page. One issue I am current ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they ...

Tips for utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

Is there a way to obtain the URL before the page finishes loading, even if the specified waiting time for the webdriver has expired?

Currently, I am attempting to retrieve the URL even if the page is still in the process of loading. However, my goal is to only obtain the URL after a specified wait time of 10 seconds has passed and then trigger a custom exception. I have experimented w ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

I have a Dart Function that needs to be converted to work with Vue.js axios.post() functionality

Here is a Dart function for uploading a selected image to a Node server. I want to implement this functionality using Vue.js. var stream = new http.ByteStream(DelegatingStream.typed(file.openRead())); var length = await file.length(); var uri = ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

Obtaining the date and time in PHP using the format yyyy-mm-ddThh:mm:ss.uZ

I have reviewed the following question and responses: How can I achieve the format of “yyyy-MM-ddTHH:mm:ss.fffZ” in php? The answers provided include references to Microsoft documentation for formatting dates, which do not apply to PHP. The top answe ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

What is the best way to extract the geometry information from a gltf object?

I've been using three.js to load a gltf file with the gltfloader, and now I'm trying to create a particle system. However, I'm having trouble getting the geometry object that I need. function initModel() { var planeGeometry = new THREE ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

The detailed record of this run can be accessed at:

npm ERR! code ENOTEMPTY npm ERR! syscall rename npm ERR! path /usr/local/lib/node_modules/expo-cli npm ERR! dest /usr/local/lib/node_modules/.expo-cli-dKBr48UN npm ERR! errno -39 npm ERR! ENOTEMPTY: The directory cannot be renamed because ...

Can you explain the purpose of the _app.js and _document.js files in Next.js? What is the significance of using an underscore (_) in Next.js?

After using npx create-next-app to create a next.js app, I noticed that there are 2 JavaScript files named app and document in the pages directory with an initial underscore. What is the purpose of this naming convention? The files appear like this: ▼ p ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Harnessing the power of JavaScript to dynamically extract data from JSON formats

My goal is to extract multiple strings from a JSON object and combine them into one large string. Initially, I thought it made sense to use a loop that would add each new string during each iteration. However, upon implementation, some unexpected errors ar ...