Step-by-step guide to implementing a month and year date-picker in Mozilla Firefox

I'm looking to create input fields where users can add the month and year. I tried using the code below, but unfortunately Mozilla Firefox doesn't support it.

<input type="month" id="start" name="start">

Does anyone have an alternative solution for adding the month and year that works in all browsers?

Answer №1

Maybe you could attempt

The primary approach

// defining variables
var nativePicker = document.querySelector('.nativeDatePicker');
var fallbackPicker = document.querySelector('.fallbackDatePicker');
var fallbackLabel = document.querySelector('.fallbackLabel');

var yearSelect = document.querySelector('#year');
var monthSelect = document.querySelector('#month');

// initially hide fallback
fallbackPicker.style.display = 'none';
fallbackLabel.style.display = 'none';

// check if date input falls back to text input
var test = document.createElement('input');

try {
  test.type = 'month';
} catch (e) {
  console.log(e.description);
}

// if it does, execute code inside the if() {} block
if(test.type === 'text') {
  // hide native picker and display fallback
  nativePicker.style.display = 'none';
  fallbackPicker.style.display = 'block';
  fallbackLabel.style.display = 'block';

  // dynamically populate years
  populateYears();
}

function populateYears() {
  // get current year as number
  var date = new Date();
  var year = date.getFullYear();

  // Make this year, and the 100 years before it available in the year <select>
  for(var i = 0; i <= 100; i++) {
    var option = document.createElement('option');
    option.textContent = year-i;
    yearSelect.appendChild(option);
  }
}
<form>
  <div class="nativeDatePicker">
    <label for="month-visit">What month would you like to visit us?</label>
    <input type="month" id="month-visit" name="month-visit">
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">What month would you like to visit us?</p>
  <div class="fallbackDatePicker">
    <div>
      <span>
        <label for="month">Month:</label>
        <select id="month" name="month">
          <option selected>January</option>
          <option>February</option>
          <option>March</option>
          <option>April</option>
          <option>May</option>
          <option>June</option>
          <option>July</option>
          <option>August</option>
          <option>September</option>
          <option>October</option>
          <option>November</option>
          <option>December</option>
        </select>
      </span>
      <span>
        <label for="year">Year:</label>
        <select id="year" name="year">
        </select>
      </span>
    </div>
  </div>
</form>

Alternatively, utilize a JS library

http://jsfiddle.net/yLjDH/

Answer №2

I approached this problem in a way that reminded me of using rgedit.

My solution involved creating two arrays: one for months and the other for years (I only considered the current year and the next two years). Here's how I did it:

[new Date().getFullYear(), new Date().getFullYear() + 1,  new Date().getFullYear() + 2,]

Then, I used two select tags to iterate through the months and years, ultimately generating the necessary date.

let date = myMonth + '-' + myYear
let newDate = new Date(date)

With the month and year values, I was able to determine the first and last days of the month.

Although the process isn't elegant, it gets the job done! Thank you for your help.

Answer №3

The type="month" element is compatible with the following browser versions:

Chrome 25.0, Edge 12.0, Opera 10.1, Firefox and Safari do not support the input type month

To work around this limitation, you can use the following code snippet:

<select id="year">
    <option value="2022">2022</option>
    <option value="2023">2023</option>
...
</select>

<select id="month">
    <option value="01">January</option>
    <option value="02">February</option>
...
</select>
const yearSelect = document.getElementById('year');
const monthSelect = document.getElementById('month');

yearSelect.addEventListener('change', updateYear);
monthSelect.addEventListener('change', updateMonth);

function updateYear() {
    const selectedYear = yearSelect.value;
    console.log('Selected year:', selectedYear);
}

function updateMonth() {
    const selectedMonth = monthSelect.value;
    console.log('Selected month:', selectedMonth);
}

While not the most elegant solution, this workaround serves my purpose well for generating stock reports.

Answer №4

SOLUTION

— The setDate() function changes the day of the month in a date object.

const date = new Date();
date.setDate(10);

— To specify a particular day for a date:

const customDate = new Date("February 14, 2022");
customDate.setDate(28);

— Use setMonth() to modify the month of a date (January is 0, February is 1, and so on).

Set the month to 7 (August):

const today = new Date();
today.setMonth(7);

— Change both the month and the day to create a specific date:

const newDate = new Date();
newDate.setMonth(3, 15);

— Call setFullYear() to update the year in a date object. This function can also adjust the month and day.

const currentYear = new Date();
currentYear.setFullYear(2024);

const specialDate = new Date();
specialDate.setFullYear(2024, 6, 30);

Answer №5

ANSWER

To implement the input type date in dd-mm-yyyy format, we utilize the type attribute. This attribute specifies a date picker or control field and allows us to set the range within which the date can be selected, from day-month-year to day-month-year. If no min and max values are provided, the default minimum value is "01-01-1920" and the default maximum value is "01-01-2120".

body {
    text-align: center;
}
h1 {
    color: green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h3>Get input date in dd-mm-yyyy format</h3>
    
    <label for="start"> Enter the Date: </label>
    
    <input type="date" name="begin" 
        placeholder="dd-mm-yyyy" value=""
        min="1997-01-01" max="2030-12-31">
</body>
</html>

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

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...

What sets MongoDB Shell Scripting apart from JavaScript?

I'm currently working on a homework assignment and I prefer not to share my code as it would give away the solution. However, I can provide some generic snippets. I must admit, I am a novice when it comes to javascript and Mongo, and I only learned ab ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...

It appears that the font in style.css is not being updated properly and seems to resemble

My issue lies within my CSS code. The text on my website is not displaying correctly and seems to be ignoring the styling that I have applied. Even though I have used similar styling on other buttons which look fine, this specific text element is causing p ...

Using AJAX for uploading files upon a change event rather than upon submission

Below is the code I have been using to implement an iframe for ajax file upload without refreshing the page upon form submission. The current code works as expected. window.onload=init; function init() { document.getElementById('form').onsubmi ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Having trouble with CSS :before pseudo-element and sibling selector?

Looking for a CSS solution to change the appearance of a triangle when the .hide class is activated within my markup. I attempted using a pseudo-element like so: summary:before { content: '\25BC'; } summary:before + .hide { con ...

Is there a way to stop a specific route in Express from continuing further execution without completing its function?

In my post route, I need to ensure that the user has provided all the necessary data in the body. To achieve this, I have added an if block to check for errors. router.post("/", (req, res) => { if(req.body.age < 24) { res.send("You are too you ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Incorporate various style components to enhance the appearance of an item in ExtJS

I'm attempting to add ellipsis to an item created by ExtJS. My goal is to only modify this item without adding any additional CSS files. After researching, I discovered there is a "style" parameter that accepts CSS styles and attempted the following: ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Glitches and sudden jumps occur when using the useMediaQuery function in Material UI

Implementing Material UI's useMediaQuery() hook, I have embedded the theme provider and initialized a variable in this way: const theme = useTheme(); const isSmall = useMediaQuery(theme.breakpoints.down('sm') ); I am utilizing the isSmall v ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

Is there a way to pass information from Express.js to React without using an API?

My goal is to build a Multi Page APP using both react and express. I find myself uncertain about how to access data sent by express in react without utilizing an API. I am curious if react has the capability to retrieve information stored in HTML props t ...

Bootstrap for Twitter: How to Customize Text in the Navigation Bar

As per the twitter bootstrap guidelines, I am supposed to enclose text in a <p> tag for correct leading and color. However, when I try to do this within the navbar element or any of its sub-levels, the text does not inherit any of the styling propert ...

Avoid relying on automated CSS generation

In my _layout.scss file, I have the SCSS code snippet below: .wrap { display: flex; flex-wrap: wrap; } After compilation, the above SCSS is automatically transformed to the following CSS. However, I want to exclude the (display: -webkit-box;) pro ...

Using jQuery to calculate mathematical operations in a form

I've been working on creating a form that calculates the total cost based on selected options. So far, I've managed to get it working for three options, but I'm stuck on how to calculate the subtotal by adding the variables "vpageprice" and ...

Exploring the capabilities of Node.js functions

I'm currently exploring Node.js and struggling to understand how functions are created and used. In my code snippet: var abc={ printFirstName:function(){ console.log("My name is abc"); console.log(this===abc); //Returns true ...